【问题标题】:How in (recursive relationship) set dinamic relationship如何在(递归关系)中设置动态关系
【发布时间】:2021-06-23 14:33:16
【问题描述】:

在这段代码中

class Topic(models.Model):
   title = models.CharField(max_length=100)
   user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
   rel = models.ManyToManyField('self', related_name='topics',
                             related_query_name='topic', blank=True)

如果我们有 3 种关系,例如 sub mid supper。 我想说

如果 topic2 是 topic1 的中间,那么关系是中间的 和 如果 topic2 是 topic1 的子,那么 topic1 是 topic2 的晚餐

我怎样才能做到这一点?

【问题讨论】:

    标签: django-models django-signals


    【解决方案1】:

    我发现我可以使用through 为多对多领域的关系创建新类。新班级应该得到 2

    class Topic(models.Model):
      title = models.CharField(max_length=100)
      user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
      related_topics = models.ManyToManyField('self', symmetrical=False, 
              through='TopicRelationship', blank=True)
    
      def __str__(self):
          return self.title
    

    为了关系

    class TopicRelationship(models.Model):
      topic1 = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name='topic1')
      topic2 = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name='topic2')
      REL_TYPES = [
          ('sub', 'sub_topic'),
          ('mid', 'mid_topic'),
      ]
      rel_type = models.CharField(max_length=3, choices=REL_TYPES, blank=True)
      class Meta:
            unique_together = ('topic1', 'topic2')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-02
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 1970-01-01
      • 2014-12-06
      相关资源
      最近更新 更多