Eric Lee
Eric Lee

Reputation: 710

Django 1.9 How do you filter child's child's model with or statement?

I have a parent model Catalog and its child model Product and Product's child model Options. Catalog and Product's relationship is OneToOne and Product and Options's relationship is OneToMany

I'd like to filter if one of Options is met a condition, return Catalog model

here is my code below

class Catalog(models.Model):
    product = models.ForeignKey(models.Product)

class Product(models.Model):
    objects = ProductManager()

class ProductOptions(models.Model):
    product = models.ForeignKey(Product, related_name = 'options')

class ProductManager(models.Manager):
    def get_queryset(self):
        queryset = super(ProductManager, self).get_queryset()
        queryset = queryset.prefetch_related('options')
        return queryset

and What I've tried so far is

this query works fine without or statement

catalog_query = models.Catalog.objects.all()
catalog_query = catalog_query.filter(product__options__date=datetime(2018,10,24)

but when i put or statement, it returns duplicated Catalog data

catalog_query = models.Catalog.objects.all()
catalog_query = catalog_query.filter(product__options__date=datetime(2018,10,24) | catalog_query.filter(product__quantity_limit=True)

Upvotes: 0

Views: 159

Answers (1)

Marpop
Marpop

Reputation: 36

You need "Q object": https://docs.djangoproject.com/pl/2.1/topics/db/queries/#complex-lookups-with-q-objects

example from documentation:

Q(question__startswith='Who') | Q(question__startswith='What')

so your example will look like that:

from django.db.models import Q

catalog_query = catalog_query.filter(
    Q(product__options__date=datetime(2018,10,24))
    | Q(catalog_query.filter(product__quantity_limit=True))

Use ".distinct()" on queryset to remove duplicates:

https://docs.djangoproject.com/pl/2.1/ref/models/querysets/#django.db.models.query.QuerySet.distinct

Upvotes: 1

Related Questions