Django Nested Filter Values - django

This line works and returns the value that I'm looking for:
logs = Log.objects.filter(filterURI=aFilter.uri).values()[0]['yk']
However, when I try to add another filter and do the same I get errors:
logs = Log.objects.filter(filterURI=aFilter.uri).filter(k=k-1).values()[0]['yk']
My understanding is that a object.filter returns a queryset but so does a 'filter of a filter'. So I should be able to do the 'values' call in the same way regardless of whether I have one filter or 1000.
What am I doing wrong here.
Thanks in advance.

I don't think the error is in the fact that you have two filters - it's in the actual second filter. k=k-1 will only work if you have both a model field and a local variable called k - the first is on the left of the expression, the second on the right.
If you want to refer to the model field on the right of the expression, use F:
.filter(k=(F('k')-1)

Related

Database query failing in django views when using filter

Just going through the Django tutorial and am playing around and testing stuff.
My question is, how come the following line works and lets me go to page no problem:
test = Choice.choices.all()
While the following filter line gives me the error message ValueError: too many values to unpack (expected 2)
test = Choice.choices.get("question_id=6")
Even when I try the following two lines it doesn't work. No idea what's happening or why
test = Choice.choices.get("question_id=6")[0]
test = Choice.choices.get("question_id=6")[0].question_text
I feel like i need to really understand what's going on and why so I can actually do proper queries in the future
That's because of a syntax error. It should be:
test = Choice.choices.get(question_id="6")
or, if the question_id field is int (pretty sure it is):
test = Choice.choices.get(question_id=6)
Basically, what's inside the bracket (parameter) is the Django translation of a SQL WHERE condition, where you can specify what field and what value to include in the result.
Infact, it corresponds to: SELECT * FROM table WHERE question_id=6
You put this where condition inside a string, but the .get() method doesn't accept a string.
Let me know whether it works!

Django Array contains a field

I am using Django, with mongoengine. I have a model Classes with an inscriptions list, And I want to get the docs that have an id in that list.
classes = Classes.objects.filter(inscriptions__contains=request.data['inscription'])
Here's a general explanation of querying ArrayField membership:
Per the Django ArrayField docs, the __contains operator checks if a provided array is a subset of the values in the ArrayField.
So, to filter on whether an ArrayField contains the value "foo", you pass in a length 1 array containing the value you're looking for, like this:
# matches rows where myarrayfield is something like ['foo','bar']
Customer.objects.filter(myarrayfield__contains=['foo'])
The Django ORM produces the #> postgres operator, as you can see by printing the query:
print Customer.objects.filter(myarrayfield__contains=['foo']).only('pk').query
>>> SELECT "website_customer"."id" FROM "website_customer" WHERE "website_customer"."myarrayfield_" #> ['foo']::varchar(100)[]
If you provide something other than an array, you'll get a cryptic error like DataError: malformed array literal: "foo" DETAIL: Array value must start with "{" or dimension information.
Perhaps I'm missing something...but it seems that you should be using .filter():
classes = Classes.objects.filter(inscriptions__contains=request.data['inscription'])
This answer is in reference to your comment for rnevius answer
In Django ORM whenever you make a Database call using ORM, it will generally return either a QuerySet or an object of the model if using get() / number if you are using count() ect., depending on the functions that you are using which return other than a queryset.
The result from a Queryset function can be used to implement further more refinement, like if you like to perform a order() or collecting only distinct() etc. Queryset are lazy which means it only hits the database when they are actually used not when they are assigned. You can find more information about them here.
Where as the functions that doesn't return queryset cannot implement such things.
Take time and go through the Queryset Documentation more in depth explanation with examples are provided. It is useful to understand the behavior to make your application more efficient.

Get last record in a queryset

How can I retrieve the last record in a certain queryset?
Django Doc:
latest(field_name=None) returns the latest object in the table, by date, using the field_name provided as the date field.
This example returns the latest Entry in the table, according to the
pub_date field:
Entry.objects.latest('pub_date')
EDIT : You now have to use Entry.objects.latest('pub_date')
You could simply do something like this, using reverse():
queryset.reverse()[0]
Also, beware this warning from the Django documentation:
... note that reverse() should
generally only be called on a QuerySet
which has a defined ordering (e.g.,
when querying against a model which
defines a default ordering, or when
using order_by()). If no such ordering
is defined for a given QuerySet,
calling reverse() on it has no real
effect (the ordering was undefined
prior to calling reverse(), and will
remain undefined afterward).
The simplest way to do it is:
books.objects.all().last()
You also use this to get the first entry like so:
books.objects.all().first()
To get First object:
ModelName.objects.first()
To get last objects:
ModelName.objects.last()
You can use filter
ModelName.objects.filter(name='simple').first()
This works for me.
Django >= 1.6
Added QuerySet methods first() and last() which are convenience methods returning the first or last object matching the filters. Returns None if there are no objects matching.
When the queryset is already exhausted, you may do this to avoid another db hint -
last = queryset[len(queryset) - 1] if queryset else None
Don't use try...except....
Django doesn't throw IndexError in this case.
It throws AssertionError or ProgrammingError(when you run python with -O option)
You can use Model.objects.last() or Model.objects.first().
If no ordering is defined then the queryset is ordered based on the primary key. If you want ordering behaviour queryset then you can refer to the last two points.
If you are thinking to do this, Model.objects.all().last() to retrieve last and Model.objects.all().first() to retrieve first element in a queryset or using filters without a second thought. Then see some caveats below.
The important part to note here is that if you haven't included any ordering in your model the data can be in any order and you will have a random last or first element which was not expected.
Eg. Let's say you have a model named Model1 which has 2 columns id and item_count with 10 rows having id 1 to 10.[There's no ordering defined]
If you fetch Model.objects.all().last() like this, You can get any element from the list of 10 elements. Yes, It is random as there is no default ordering.
So what can be done?
You can define ordering based on any field or fields on your model. It has performance issues as well, Please check that also. Ref: Here
OR you can use order_by while fetching.
Like this: Model.objects.order_by('item_count').last()
If using django 1.6 and up, its much easier now as the new api been introduced -
Model.object.earliest()
It will give latest() with reverse direction.
p.s. - I know its old question, I posting as if going forward someone land on this question, they get to know this new feature and not end up using old method.
In a Django template I had to do something like this to get it to work with a reverse queryset:
thread.forumpost_set.all.last
Hope this helps someone looking around on this topic.
MyModel.objects.order_by('-id')[:1]
If you use ids with your models, this is the way to go to get the latest one from a qs.
obj = Foo.objects.latest('id')
You can try this:
MyModel.objects.order_by('-id')[:1]
The simplest way, without having to worry about the current ordering, is to convert the QuerySet to a list so that you can use Python's normal negative indexing. Like so:
list(User.objects.all())[-1]

How to get a list of queryset and make custom filter in Django

I have some codes like this:
cats = Category.objects.filter(is_featured=True)
for cat in cats:
entries = Entry.objects.filter(score>=10, category=cat).order_by("-pub_date")[:10]
But, the results just show the last item of cats and also have problems with where ">=" in filter. Help me solve these problems. Thanks so much!
You may want to start by reading the django docs on this subject. However, just to get you started, the filter() method is just like any other method, in that it only takes arguments and keyword args, not expressions. So, you can't say foo <= bar, just foo=bar. Django gets around this limitation by allowing keyword names to indicate the relationship to the value you pass in. In your case, you would want to use:
Entry.objects.filter(score__gte=10)
The __gte appended to the field name indicates the comparison to be performed (score >= 10).
Your not appending to entries on each iteration of the for loop, therefore you only get the results of the last category. Try this:
entries = Entry.objects.filter(score__gte=10, category__is_featured=True).order_by("-pub_date")[:10]

Output location of images for django-imagekit

I'm trying to output a list of images that belong to each record in my app as below:
pri_photo = vehicle.images.all()[:1]
sec_photos = vehicle.images.all()[1:]
This first part is OK. The part I'm having issues with is when I try
pri_photo.original_image.url
sec_photos.original_image.url
The above two lines of code give me a 'QuerySet' object has no attribute 'original_image'. What could be the issue?
I also want the photos in sec_photos to be output as image1, image2,... upto the last one
[:1] just limits the number of records returned by the queryset, still it is a queryset result, not a single object.
to get a single object, you shoud use
[0]
or
[0:1].get()
but it's not safe, as it will raise an error if none objects match the query. to do it properly, use filter() and if result are present then get(), or
try:
#get()
except modelname.DoesNotExist:
# do shomething else
also, if you are looking for the latest object, maybe you can just use http://www.djangoproject.com/documentation/models/get_latest/