xpanta
xpanta

Reputation: 8418

django models, applying filter() on joined table with extra()

I am trying this:

count = UserCheck.objects.filter(user=puser, fixture__competition__name__icontains='gold',
                                   fixture__date__gte='2013-02-11',
                                   fixture__date__lte='2013-05-24', year=2013).extra(
                                   where=["WEEKOFYEAR(fixture__date) = %s" %week]).exclude(result=0).count()

The problem is the extra() part where I can't filter using WEEKOFYEAR(fixture__date). How can I do this. Is this possible?

PS: I am using MySQL (and django 1.4)

Upvotes: 1

Views: 544

Answers (1)

dmg
dmg

Reputation: 7706

When using the extra QuerySet modifier, you are not using Django's ORM anymore. You are using "pure" SQL, so basically related models can't be accessed with the __ notation and in your case fixture__date is not a valid column name. However, one must keep in mind that tables are named in a specific way in Django. So you can use:

count = UserCheck.objects.filter(user=puser, fixture__competition__name__icontains='gold',
                                   fixture__date__gte='2013-02-11',
                                   fixture__date__lte='2013-05-24', year=2013).extra(
                                   where=["WEEKOFYEAR(app_fixture.date) = %s" %week]).exclude(result=0).count()

where app refers to the app that holds the Fixture model.

In short, for each model in an app, Django makes the table <app>_<model>, and you can use that with the extra clause when you want to refer to that model.

Upvotes: 3

Related Questions