Django 注释反向关系

发布于 2024-07-24 01:58:05 字数 157 浏览 6 评论 0原文

当使用 django.contrib.comments 时,是否可以将反向关系添加到有注释的模型中?

例如:

post = Post.objects.all()[0]
comments = post.comments.all()

When using django.contrib.comments is there anyway to add the reverse relationship to a model that has comments?

For example:

post = Post.objects.all()[0]
comments = post.comments.all()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苦行僧 2024-07-31 01:58:05

是的,您应该能够执行以下操作:

from django.contrib.contenttypes import generic
class Post(models.Model):
    ...
    comments = generic.GenericRelation(Comments)

根据 反向泛型关系

Yes, you should be able to do:

from django.contrib.contenttypes import generic
class Post(models.Model):
    ...
    comments = generic.GenericRelation(Comments)

per the Django docs on reverse generic relations

梦开始←不甜 2024-07-31 01:58:05

我想出了另一种方法来做到这一点(为什么?因为当时我不知道有任何其他方法可以做到这一点)。 它依赖于一个抽象模型类,系统中的所有模型都是从该抽象模型类派生的。 抽象模型本身有一个方法,comments,定义为在调用时返回与相应具体对象关联的所有注释对象的 QuerySet。 我是这样实现的:

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.comments.models import Comment

class AbstractModel(models.Model):

    def comments(self):
        """Return all comment objects for the instance."""
        ct = ContentType.objects.get(model=self.__class__.__name__)
        return Comment.objects.filter(content_type=ct,
                                    object_pk=self.id)

    class Meta:
        abstract = True

I came up with another way to do this (why? Because I wasn't aware of any other way to do that time). It relies on having an abstract model class from which all models in the system are derived. The abstract model itself has a method, comments, defined which when called returns a QuerySet of all the comment objects associated with the corresponding concrete object. I implemented it thus:

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.comments.models import Comment

class AbstractModel(models.Model):

    def comments(self):
        """Return all comment objects for the instance."""
        ct = ContentType.objects.get(model=self.__class__.__name__)
        return Comment.objects.filter(content_type=ct,
                                    object_pk=self.id)

    class Meta:
        abstract = True
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文