I'm not sure if the title is correctly describing the issue. If you have a more descriptive title, please edit the title.
I have a following dynamically added input fields:
The first two rows is the first object, second row is the second object, and so on.... I am trying to save these dynamically added elements to DB by customizing post() method.
Using my current version of overriding post() method:
if 'bha' in request.POST:
bha_form = BHA_Form(request.POST, instance= #some_kwargs...)
print(request.POST)
it prints the following queryset:
<QueryDict: {'csrfmiddlewaretoken': [# foo_token], 'item_description': ['aaaaaaaaa', 'bbbbbbbbb'], 'num_of_jts': ['aaaaaaaaaaa', 'bbbbbbbbb'], 'length': ['aaaaaaaaaaaa', 'bbbbbbbbbb'], 'cum_length': ['aaaaaaaaaaaaa', 'bbbbbbbbbbbbbb'], 'outer_d': ['aaaaaaaaaaaaa', 'bbbbbbbbbbbbbbb'], 'inner_d': ['', ''], 'drift_d': ['', ''], 'od_cplg': ['', ''], 'top_thread': ['', ''], 'air_wght': ['', ''], 'make': ['', ''], 'sn': ['', ''], 'bha_component': ['Submit']}>
As you can see, each input fields have 2 values in a form of list, because there are two objects present on the Front-End. If I just use bha_form.save(), it will save only the last value in a queryset list. This is not what I want. I want to use something like get_or_create() method to create new objects for each dynamically added elements, or edit objects if they are already present in DB
How should I do this? I guess I can write some long set of codes to get this done, but just curious if there's any elegant way of achieving this.
You can use Django Formsets that do exactly what you're asking for : posting many objects at the same time. It is a very clean way to do so.
The documentation in the link above explains how to use it in details.
Related
have a simple request to Solr below
response = requests.get("http://localhost:8080/solr/select?fl=id,title,description,keywords,author&q=domain:mydomain.com&rows=10&indent=on&wt=json&omitHeader=true")
result = response.json()
print type(result)
print result
print response.text
the above code fives me the following output
the type
<type 'dict'>
the dict contents
{u'response': {u'start': 0, u'numFound': 1, u'docs': [{u'keywords': u'my keywords listed here', u'id': u'project.websiteindex.abe919664893e46eef21aacb1360948ae836a756faa28e2063a4a92ef4273630', u'description': u'my site description isted here.', u'title': u'my site title'}]}}
and below the better readable vesion
{
"response":{"numFound":1,"start":0,"docs":[
{
"description":"my site description isted here.",
"title":"my site title",
"keywords":"my keywords listed here",
"id":"project.websiteindex.abe919664893e46eef21aacb1360948ae836a756faa28e2063a4a92ef4273630"}]
}}
executing:
print(result['response']['numFound'])
will give me the very useful output of
1
Very nice and all, but obviously i would like to get something like
print(result['response']['title'])
my site title
So my question, how do i get my values of title,description and keywords as keys
How do i select them using this format, or how do i get my desired values in a better dict format?
p.s.
stuck wioth an old setup here with python 2.7 and solr 3.6
Since the values you are addressing are fields of an array element, you have to address the element first.
Try something like:
result['response']['docs'][0]['title']
I am trying to create an API endpoint. Here I am using MultiPart/form-data content-type to cater multiple input types. But I am stuck in MultiPartParser.
my view function declaration is something like this:
#api_view(['GET','POST','PUT'])
#parser_classes([MultiPartParser,JSONParser])
def item_view(request):
The MultiPartParser is parsing this:
<QueryDict: {'code': ['3'], 'gst_rate': ['5']}> <MultiValueDict: {}>
What I want:
<QueryDict: {'code':3, 'gst_rate':5}> <MultiValueDict: {}>
How can I do that?
It isn't because of MultiPartParser. Even if you are just using e.g. JSONParser, the value will still be a list because query parameters are string based, thus there can be duplicates.
http://127.0.0.1:8000/my_app/some_random_api4/?code=3&gst_rate=5&code=7
Here, the query string is ?code=3&gst_rate=5&code=7. We can see that there are 2 values for the same field code, which are "3" and "7".
Code
print(f"{request.query_params=}")
for param_name in request.query_params.keys():
print(param_name)
print("\t", request.query_params.getlist(param_name))
print("\t", request.query_params.get(param_name))
print(f"\t {request.query_params[param_name]=}")
Output
request.query_params=<QueryDict: {'code': ['3', '7'], 'gst_rate': ['5']}>
code
request.query_params.getlist(param_name)=['3', '7']
request.query_params.get(param_name)='7'
request.query_params[param_name]='7'
gst_rate
request.query_params.getlist(param_name)=['5']
request.query_params.get(param_name)='5'
request.query_params[param_name]='5'
Here, we can see that the QueryDict reflects the list of codes "3" and "7" as with the getlist() operation, while the the get() and [] (__getitem__()) only gets the one value, here being the last which is "7".
Instead of manually calling get() or [] or items() on the QueryDict, we can simply use dict() (unless you want to change the implementation to get the first value in the list instead of the last):
Code
query_params_updated = request.query_params.dict()
print(f"{query_params_updated=}")
Output
query_params_updated={'code': '7', 'gst_rate': '5'}
I want to set 'unique_together' on my DB (postgres). The problem is that I may already have duplicates on DB, so migration would probably not work. So as I see it - before the deployment I need to run some script to remove all duplications (leave only one of each). I prefer doing it with Django Custom Command.
The table 'mapping' looks something like - Id, user_id, user_role, project_id, user_type.
I want to set 'unique_together' for all of them.
And the script I use to retrieve duplicated rows is-
duplicates = (Mapping.objects.values('project_id', 'user_id', 'user_type', 'user_role').annotate(
count=Count('id')).values('project_id', 'user_id', 'user_type', 'user_role').order_by().
filter(count__gt=1))
It returns list of objects that contains the duplicated attributes.
for example:
QuerySet [{'user_id': '2222', 'user_type': '1', 'user_role': '1', 'project_id': UUID('c02bda0e-5488-4519-8f34-96b7f3d36fd6')}, {'user_id': '44444', 'user_type': '1', 'user_role': '1', 'project_id': UUID('8c088f57-ad0c-411b-bc2f-398972872324')}]>
Is there a way to retrieve the Ids directly?
Is there a better way?
You can try it:
Mapping.objects.values(
'project_id', 'user_id', 'user_type', 'user_role'
).annotate(count=Count('id')
).annotate(max_id=Max('id')
).values('max_id').order_by().filter(count__gt=1)
How can I resolve a resource_uri during a Tastypie hydrate call?
I am passing the following data object to a Tastypie resource:
{
'date': u'2013-10-31 15:06',
'visitor': u'/visitorlog/api/v1/person/33/',
'purpose': u'Testing'
}
I would like to take the visitor and pull the entire record in a hydrate function, which populates a field with some extra information.
I am currently doing this by splitting out the id and performing a search:
def hydrate_meta(self, bundle):
'''
This will populate the `meta` field with a snapshot of the employee record, if the `empid` is set. This is done so if the employee record changes we retain certain information at the time of the visit.
'''
split_id = bundle.data['visitor'].split('/')
# the id of `visitor` is in `split_id[-2]
# get the record of this visitor from the Django model
person_record = Person.objects.get(pk = split_id[-2])
# ... snipped ... create the `meta_value` object
bundle.data['meta'] = meta_values
return bundle
This is working, but calling split on the resource_uri does not seem the most elegant way to do this.
Is there more effective way to pull a record given a resource_uri?
Resource.get_via_uri(url) (doc) might come in handy.
I'm trying to work with m2m fields.
What I want to do is to have a string (CharField) where user can write the tags of a post, with each tag separated by commas.
I was able to do the creation in this way:
tags = tags.split(',')
for tag in tags:
obj, create = Tag.objects.get_or_create(name=tag)
pub.tags.add(obj)
Now, I want to do the UpdateView. Obviously if I don't specify the conversion from list to string in the form, I don't have any value set. So it should be something like:
for tag in tags:
str+=tag+","
The point is:
Do I have to write the conversion of list to string and string to list each time?
Can i specify somewhere how to do this conversion? Is there anything already implemented in Django?
PS: In the UpdateView, if I remove a tag, how can I remove it from the relation as well since I have to do the parsing by hand?
Thanks.
The simplest way is to remove all the tags from pub.tags first, then add them all back in:
# Clear the existing tags
pub.tags.clear()
tags = tags.split(',')
for tag in tags:
obj, create = Tag.objects.get_or_create(name=tag)
pub.tags.add(obj)
Instead of looping and building a String, you might try this more pythonic method:
tags = ['red', 'green', 'blue']
','.join(tags)
'red,green,blue'