How to display only ID field Django - django

I would like to solve a little problem with Django and QuerySet.
I have in my views this command :
query_car = Car.objects.get(pk=value)
But I want to get only one field from the CarModels, for example : color or another one but just one.
How I can handle my script in order to do that ?
Thank you so much !

You should use .values()
example:
query_car = Car.objects.filter(pk=value).values('color')

You are looking for the only() method.
Like so:
query_car = Car.objects.only("color").get(pk=value)

Related

Filtering object model django with list of values

I am building a django project and I have a list of ids [23,44,12,67] and I have a model named testmodel
tests = testmodel.objects.all()
But I want to remove/filter(I don't want to remove from database, just filter) the objects which has the ids in my list. Any help how I can achieve this in a simple way using django ?
You need the .exclude() ORM method:
testmodel.objects.exclude(id__in=[23,44,12,67])
tests = testmodel.objects.exclude(id__in=[23, 44, 12, 67])
try this:
test = testmodel.objects.exclude(pk__in=[23,44,12,67])
You can find more information here

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.

Django taggit doesn't work exclude

I am using Django-taggit and works fine for me but the exclude has a problem.
Keyword is a string like 'key1 key2 key3'. The code is:
keyword = form.cleaned_data['keyword']
qlist = lambda x: [Q(name__icontains=x), Q(author__name__icontains=x),Q(tags__name__icontains=x)]
item_list = Item.objects.distinct()
for key in keyword.split():
if ('-'==key[0]):
print 'exclude: %s'%(key[1:])
item_list = item_list.exclude(reduce(operator.or_,qlist(key[1:])))
else:
print 'include: %s'%(key)
item_list = item_list.filter(reduce(operator.or_,qlist(key)))
It works fine for filter() and for the exclude() Q(name_icontains=x), Q(author_name_icontains=x).
But, when I try to use exclude() with Q(tags_name__icontains=x) it doesnt work.
Regards,
Cristian
I'm not really too versed in taggit intricacies, but... Looking at the code, it seems like the "name" is dynamically built in a lazy way.
So, if you're not populating the query explicitly, you're going to get empty request, so Q(tags__name__icontains=key) will be empty, and exclude(...) will just be like filter(not null).
Try to force populating the tag query via a select_related() or something similar.
I think, It is not supported. I found this link:
https://github.com/alex/django-taggit/issues/31

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)