Django QuerySet用于通过多对多相关的对象

时间:2018-09-19 18:26:05

标签: django django-rest-framework

我有以下型号:

file

我目前正在尝试获取特定城市(例如“纽约”)上所有可用产品的列表。由于产品通过商店中的菜单通过ManyToMany关联,因此我不确定100%运行此查询的最佳方式是什么。

我知道如何更深入地研究相关对象,例如:

class Brand(models.Model):
    owner = models.ForeignKey(Account, on_delete=models.DO_NOTHING)
    name = models.CharField(max_length=128)

class Product(models.Model):
    owner = models.ForeignKey(Account, on_delete=models.DO_NOTHING)
    brand = models.ForeignKey(Brand, blank=True, null=True, on_delete=models.DO_NOTHING)

class Store(models.Model):
    owner = models.ForeignKey(Account, on_delete=models.DO_NOTHING)
    name = models.CharField(max_length=128)
    menu = models.ManyToManyField(Product)
    address = models.ForeignKey(Address, on_delete=models.DO_NOTHING, blank=True, null=True)

class Address(models.Model):
    address_1 = models.CharField(max_length=255)
    address_2 = models.CharField(max_length=255, blank=True, null=True)
    city = models.CharField(max_length=255)

但是如何从Product对象进入商店?

3 个答案:

答案 0 :(得分:0)

类似这样的东西:

ids = Store.objects.filter(address__city='New York').values_list('menu', flat=True)
result = Product.objects.filter(id__in=ids)

答案 1 :(得分:0)

尝试一下:

Product.objects.filter(store__address__city='New York')

我已经为您验证了这一点。

enter image description here

如果您要从产品中购买商品,请尝试product_object.strore_set.all()

顺便提一句,您的模型设计似乎store__address__city=search非常有意义。但是您拥有像每个模型一样的所有者,可能就是您的业务需求。

答案 2 :(得分:0)

要通过产品对象在纽约开店,请尝试类似的事情。

class Store(models.Model):
   owner = models.ForeignKey(Account, on_delete=models.DO_NOTHING)
   name = models.CharField(max_length=128)
   menu = models.ManyToManyField(Product, related_name='stores') #add related_name here to access stores for a product
   address = models.ForeignKey(Address, on_delete=models.DO_NOTHING, blank=True, null=True)

然后,您将获得商品的商店,并筛选出纽约的商品。

product.stores.filter(address__city='New York')
相关问题