【问题标题】:Django QuerySet for objects related through a many to manyDjango QuerySet 用于通过多对多相关的对象
【发布时间】:2018-09-19 18:26:05
【问题描述】:

我有以下型号:

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)

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

我知道如何深入挖掘相关对象,例如:

Store.objects.all().filter(address__city="New York")

但是我如何从 Product 对象到达商店?

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    类似这样的:

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

    【讨论】:

    【解决方案2】:

    试试这个:

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

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

    如果您想要产品中的商店,请尝试product_object.strore_set.all()

    顺便说一句,您的模型设计似乎很好store__address__city=search 非常有意义。但是您在每个模型中都有所有者,这可能是您的业务需求。

    【讨论】:

      【解决方案3】:

      要从产品对象中获取纽约的商店,请尝试以下操作。

      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')
      

      【讨论】:

        猜你喜欢
        • 2011-06-16
        • 1970-01-01
        • 1970-01-01
        • 2019-06-19
        • 1970-01-01
        • 2021-11-24
        • 2011-10-09
        • 1970-01-01
        • 2012-04-30
        相关资源
        最近更新 更多