【问题标题】:Implementing Subsets of Foreign Keys in Django在 Django 中实现外键子集
【发布时间】:2013-05-19 12:46:19
【问题描述】:

我正在用 Django 构建一个论坛风格的网站,并且在我的设计结构中遇到了一些问题。相关代码(来自我的模型)如下所示:

class Thread(models.Model):
    post_count = models.IntegerField()

class Post(models.Model):
    text = models.CharField(max_length=1000)
    thread = models.ForeignKey(Thread)

我遇到的问题是,在我的视图和模板中,我遍历线程并显示帖子。但是,我希望向我的模板传达一个帖子可能具有某些“特殊属性”(例如,主题发起人、最新帖子、得分最高的帖子等)。对我来说,这些将是线程的属性而不是帖子本身似乎是合理的(因为每个线程都会有这些,但只有可变/可忽略的帖子数量)但是我已经设法撰写的这个问题的解决方案涉及将帖子双重链接到线程(通过 Post 定义中的另一个 ForeignKey(Thread))或通过在 Post 定义中放置 BooleanFields 以指示这些列表中的状态。我什至不确定这些在 Django 模板中是否有效或可见。

我的问题:在 Django 中是否有一种干净的方法来专门化或分组已经通过作为外键中的姐妹元素链接的模型实例,即将一个 ForeignKey 子集为单独的(并且可能重叠)组?还是我以非pythonic/nondjango 的方式解决这个问题?任何我可能忽略的见解或文档链接将不胜感激。

【问题讨论】:

    标签: django django-models django-templates foreign-keys


    【解决方案1】:

    您可能需要在 Thread 中将某些属性添加为 ManyToManyField

    class Thread(models.Model):
        post_count = models.IntegerField()
        post_latest = models.ManyToManyField(Post, related_name='as_latest', null=True, blank=True)
    

    或者,我更喜欢使用@property 来获取您需要的具有某些属性的数据:

    class Thread(models.Model):
        post_count = models.IntegerField()
    
        @property
        def post_latest(self):
            return self.post_set.order_by('-id')[:10]
    

    【讨论】:

      猜你喜欢
      • 2012-02-19
      • 2011-05-28
      • 2013-10-25
      • 1970-01-01
      • 2015-03-09
      • 2013-09-17
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      相关资源
      最近更新 更多