简体   繁体   中英

django query with Q and multiple categories

I ve got the following model structure:

class Pizza(models.Model):
    name = models.CharField(max_length=50)
    shop = models.CharField(max_length=50)


class Topping(models.Model):
    name = models.CharField(max_length=50)
    pizza = models.ManyToManyField(Pizza)

I want to find all pizzas which are with ham or cheese or both, is this the standard django way?: from django.db.models import Q

Pizza.objects.filter(Q(topping__name='ham') | Q(topping__name='cheese'))

How do i do it programatically, if i got a list of toppings, eg?:

['ham','cheese']

You could do it with dicts and **kwargs, but there's no need: easier to just use __in :

topping_list = ['ham', 'cheese']
Pizza.objects.filter(topping__name__in=topping_list)

I would definitely swap the manytomany relationship to point from Pizza to Topping. Why would you query all toppings objects first to get the list then compare it against the Pizza? I believe you mostly want to show a pizza with their toppings and not showing a list of pizzas that have a particular topping. Would make it easier I guess (unless your app is mostly about the topping)...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM