【问题标题】:Conditional related model on Django Many to Many FieldDjango多对多字段上的条件相关模型
【发布时间】:2018-05-10 07:09:41
【问题描述】:

我想知道如何实现这种行为,任何帮助将不胜感激

class ModelA(models.Model):
    pass

class ModelB(models.Model):
    pass

class ModelC(models.Model):
    TYPE = (('A', 'ModelA'), ('B', 'ModelB'))
    type = models.CharField("model type", choices=TYPE, max_length=2, unique=True)
    field = models.ManyToManyField(ConditionalModel)

我想在 ModelC 定义中做这样的事情 ->

if type="A":
    field = models.ManyToManyField(ModelA)
if type="B":
    field = models.ManyToManyField(ModelB)

【问题讨论】:

    标签: django models manytomanyfield


    【解决方案1】:

    您不能有条件 ManyToManyField 到 2 个不同的 Models
    最好的方法是使用GenericRelation,它可以接收任何模型。

    将您自己模型中的一个外键添加到 ContentType 可以让您的模型有效地将自身绑定到另一个模型类

    class TaggedItem(models.Model):
        tag = models.SlugField()
        content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
        object_id = models.PositiveIntegerField()
        content_object = GenericForeignKey('content_type', 'object_id')
    

    content_object 可以接收任何模型实例。

    【讨论】:

      【解决方案2】:

      创建 2 m2m realations 并执行以下操作

      class ModelA(models.Model):
          pass
      
      class ModelB(models.Model):
          pass
      
      class ModelC(models.Model):    
          TYPE = (('A', 'ModelA'), ('B', 'ModelB'))
          type = models.CharField("model type", choices=TYPE, max_length=2, unique=True)
          _m2m_A = models.ManyToManyField(ModelA)
          _m2m_B = models.ManyToManyField(ModelB)
      
          @property
          def field(self):
              if self.type == "A":
                 return self._m2m_A
              elif self.type == "B":
                 return self._m2m_B  
      

      【讨论】:

        猜你喜欢
        • 2019-08-17
        • 2021-10-19
        • 2020-07-01
        • 1970-01-01
        • 2011-08-05
        • 2015-10-03
        • 2012-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多