Eimantas
Eimantas

Reputation: 429

Django filter queryset if field exists

In my custom manager I would like to filter queryset if only this field has value:

class PropertyManager(gis_models.GeoManager):
    def get_queryset(self):
        return super(PropertyManager,self).get_queryset().filter(active=True, valid_until__gte = datetime.now())

The problem is that valid_until field is not required and may be null. So I would like my manager to filter objects (valid_until__gte = datetime.now()) only if this field's value has been set during object creation. If this value is null, I would only like the manager to use the first filter (active=True).

Is it possible to make such raw SQL IF statements in Django ? I am using Mysql db.

Upvotes: 2

Views: 2234

Answers (2)

GammaSQ
GammaSQ

Reputation: 391

It's also possible to exclude all not-wanted results, so in your case:

.filter(active=True).exclude(valid_until__lt=datetime.now())

This will exclude all results where valid_until is set an lower than datetime.now(), so None-values will be returned as well!

Upvotes: 0

Rohan
Rohan

Reputation: 53386

You can use Q object to combine your lookup.

You can do filter to find objects which has valid_date > now() OR valid_date=None as

.filter(Q(valid_until__gte = datetime.now()) | Q(valid_until=None))

Upvotes: 2

Related Questions