【问题标题】:how to access joining table/object of django many to many relationship如何访问 django 多对多关系的连接表/对象
【发布时间】:2017-08-08 08:55:42
【问题描述】:

我有以下型号:

class InvestmentChoice(models.Model):
    title = models.CharField(max_length=64)


class Offering(models.Model):  
    entity = models.OneToOneField(Entity) 
    investment = models.ManyToManyField(InvestmentChoice, blank=True)

创建的连接表有以下字段:

id | offering_id | investment_choice_id
1  |     277     | 5

我想获取具有特定投资选择的实体对象的列表。我认为这意味着我需要访问多对多连接表。

例如,如果我想要所有提供 Offeringinvest_choice_id 为 5 的实体。

如果是这样,我该如何使用 django 查询来做到这一点?

【问题讨论】:

    标签: python django django-models many-to-many django-orm


    【解决方案1】:

    如果您想获得所有投资为 5 的产品实体,以下查询可以完成工作。

    Offering.objects.filter(investment__id=5)
    

    如果您想获得某些投资实体的所有产品,请使用in

    from django.db.models import Q
    investments = Investment.objects.filter(Q(id=1) || Q(id=5))
    Offering.objects.filter(investment__in=investments)
    

    有关多对多查询的更多信息,您可以查看Django Doc 和查询read this documentation

    【讨论】:

      【解决方案2】:

      我可以分两步做到这一点:

      choice = InvestmentChoice.objects.get(pk=5)
      

      然后我可以获取所有相关的产品对象,例如:

      offerings = choice.offering_set.all()
      

      【讨论】:

        【解决方案3】:

        根据https://docs.djangoproject.com/en/2.0/topics/db/models/,您可以在 InvestmentChoice 模型中添加如下内容:

        entities = models.ManyToManyField(Entity, through='Offering')

        希望有帮助!

        【讨论】:

          猜你喜欢
          • 2012-04-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-19
          • 1970-01-01
          • 2019-09-18
          相关资源
          最近更新 更多