Wednesday, February 29, 2012

Re: Filtering model searches by a property (as opposed to a field)

Thank you very much for that Javier.

After flailing around with raw SQL for a while I realised that Django
has conveniently provided a powerful set of field lookups that I did
not know about.

I have ended up doing this, which is a million times simpler than what
I was previously attempting:

<views.py>
...
date = datetime.date.today()
day_of_the_week = date.weekday()
last_date_in_week = date + datetime.timedelta(days = 7 -
day_of_the_week)
week = Todo.objects.filter(owner__id =
user.id).filter(due_date__lte=last_date_in_week).filter(due_date__gt=date)
...
</views.py>

This gives me 'todo' objects from tomorrow until the end of the week,
which is what I want.

On Mar 1, 3:35 am, Javier Guerra Giraldez <jav...@guerrag.com> wrote:
> On Wed, Feb 29, 2012 at 3:16 PM, Tom <t.scr...@gmail.com> wrote:
> > Is it not possible to filter based on a property?
>
> queries are compiled to SQL to be sent and processed at the database;
> properties are Python code, the database knows nothing about them.
> that's why the compiler only allows you to use database fields on a
> filter
>
> > What is the correct method for doing this?
>
> the generic answer is to do it in Python, something like:
>
> result = [ record in queryset if record.property == value ]
>
> but this can be very inefficient, and nowhere as flexible as Django's querysets.
>
> much better is to translate the criteria into something the database
> can process.  In this case, find the beginning and end of the current
> week and use a range filter.
>
> --
> Javier

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment