Django get() query not working - django

this_category = Category.objects.get(name=cat_name)
gives error: get() takes exactly 2 non-keyword arguments (1 given)
I am using the appengine helper, so maybe that is causing problems. Category is my model. Category.objects.all() works fine. Filter is also similarily not working.
Thanks,

Do you have any functions named name or cat_name? If so, try changing them or the variable names you are using and trying again.

The helper maps the Django model manager (Category.objects in this case) back to the class instance of the model via the appengine_django.models.ModelManager. Through the inheritance chain you eventually come to appengine.ext.db.Model.get(cls, keys, **kwargs) so that is why you are seeing this error. The helper does not support the same interface for get that Django does. If you do not want to get by primary key, you must use a filter
To do your query, you need to use the GAE filter function like this:
this_category = Category.objects.all().filter('name =', cat_name).get()

Related

Filter all queries based on url parameters

I have in a Django project all my urls based on the following syntax:
/ID_PROGRAM/ID_PROJECT/blablabla
I would like by default that all my queries have the following filters:
.filter(program=ID_PROGRAM).filter(project=ID_PROJECT)
How can I apply these filters automatically to all my queries? My idea was to define a new manager. But is the manager able to access to the url parameters? I this the best way to do?
To complet the question, I want to enrich all my queries without having to pass explicitly the view parameters to the manager.
You could have just tried it to see if it works.
Yes, managers do accept parameters
class MyModelManager(models.Manager):
def my_filters(self, id_prog, id_proj):
return super(MyModelManager, self).get_query_set().filter(program=id_prog, project=id_proj)
and in the views:
MyModelManager.objects.my_filters(id_prog, id_proj)
Documentation on custom managers
Python promotes "Explicit is better than implicit"
karthikr is almost right, but you can also use:
1 - decorator above your function. Decorator will get args from url and put objects to any variable
2 - write mixin and aply it to view. Mixin will get args from url at overriden dispatch and save filter result to self.custom_context. Override get_context_data to merge contexts.

Django - Creating data with or without .create()

I'm following the official Django Tutorial and confused about this part:
Sometimes they create a model data without .create() like:
Poll(pub_date= timezone.now() )
and sometimes they use .create() like:
Poll.objects.create(pub_date= timezone.now() )
From what I run, both returns the same result. So is there any difference?
Thanks
The latter saves it in the table (performs an implicit .save()). The former does not.

Django: How to access the model id's within an AJAX script?

I was wondering what is the correct approach,
Do I create HiddenInput fields in my ModelForm and from the
View I pass in the primaryKey for the models I am about to edit into
the hiddenInput fields and then grab those hiddenInput fields from
the AJAX script to use it like this?
item.load(
"/bookmark/save/" + hidden_input_field_1,
null,
function () {
$("#save-form").submit(bookmark_save);
}
);
Or is there is some more clever way of doing it and I have no idea?
Thanks
It depends upon how you want to implement.
The basic idea is to edit 1. you need to get the existing instance, 2. Save provided information into this object.
For #1 you can do it multiple ways, like passing ID or any other primary key like attribute in url like http://myserver/edit_object/1 , Or pass ID as hidden input then you have to do it through templates.
For #2, I think you would already know this. Do something like
inst = MyModel.objects.get(id=input_id) # input_id taken as per #1
myform = MyForm(request.POST, instance=inst)
if myform.is_valid():
saved_inst = myform.save()
I just asked in the django IRC room and it says:
since js isn't processed by the django template engine, this is not
possible.
Hence the id or the object passed in from django view can't be accessed within AJAX script.

django how do i mix an order_by and a get in a listview url?

So i want to create:
select * from Post where Post.is_chosen = true order_by create_date
and i want this to occur in the urls.py (that is, not have to define anything, just stick it in the ListView parameters)
How do i do this?
I currently have:
url(r'^$',ListView.as_view(
queryset=Post.objects.get(is_chosen = True).order_by('-pub_date')[:20],
context_object_name='latest_post_list',
template_name='posts/index.html')),
but this has an error - i cannot call order_by on the return object of the "get" This makes sense, but how can i do what i want?
I am open to calling the command from a defined function if it is impossible to do in the url definition!
UPDATE: ARGH I am an idiot.
"get" only returns one item, so of course "order_by" won't work on it. I use filter instead now!
Like the docs say, use .filter() instead.

How can I get access to a Django Model field verbose name dynamically?

I'd like to have access to one my model field verbose_name.
I can get it by the field indice like this
model._meta._fields()[2].verbose_name
but I need to get it dynamically. Ideally it would be something like this
model._meta._fields()['location_x'].verbose_name
I've looked at a few things but I just can't find it.
For Django < 1.10:
model._meta.get_field_by_name('location_x')[0].verbose_name
model._meta.get_field('location_x').verbose_name
For Django 1.11 and 2.0:
MyModel._meta.get_field('my_field_name').verbose_name
More info in the Django doc
The selected answer gives a proxy object which might look as below.
<django.utils.functional.__proxy__ object at 0x{SomeMemoryLocation}>
If anyone is seeing the same, you can find the string for the verbose name in the title() member function of the proxy object.
model._meta.get_field_by_name(header)[0].verbose_name.title()
A better way to write this would be:
model._meta.get_field(header).verbose_name.title()
where header will be the name of the field you are interested in. i.e., 'location-x' in OPs context.
NOTE: Developers of Django also feel that using get_field is better and thus have depreciated get_field_by_name in Django 1.10. Thus I would suggest using get_field no matter what version of Django you use.
model._meta.get_field_by_name('location_x')[0].verbose_name
You can also use:
Model.location_x.field.verbose_name
Model being the class name. I tested this on my Animal model:
Animal.sale_price.field.verbose_name
Animal.sale_price returns a DeferredAttribute, which has several meta data, like the verbose_name
Note: I'm using Django 3.1.5
If you want to iterate on all the fields you need to get the field:
for f in BotUser._meta.get_fields():
if hasattr(f, 'verbose_name'):
print(f.verbose_name)
# select fields for bulk_update : exclude primary key and relational
fieldsfields_to_update = []
for field_to_update in Model._meta.get_fields():
if not field_to_update.many_to_many and not field_to_update.many_to_one and not field_to_update.one_to_many and not field_to_update.one_to_one and not field_to_update.primary_key and not field_to_update.is_relation :
fields_to_update = fields_to_update + [field_to_update.name]
Model.objects.bulk_update(models_to_update , fields_to_update)