Django使用多表inheritan筛选查询

2024-04-23 20:00:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Django multi-table inheritance实现一个通知系统。你知道吗

看起来是这样的:

class Notification(models.Model):
    # this allows us to check the type without having to query another table
    type = models.CharField(max_length=2, choices=type_choices)
    user = models.ForeignKey(User, related_name='+', null=True)
    date = models.DateTimeField(default=datetime.now)
    read = models.BooleanField(default=False)

    class Meta:
        ordering = ["-date"]


# Users can comment on items.
class CommentNotification(Notification):
    comment = models.ForeignKey(Comment, related_name='+')


class ShareNotification(Notification):
    share = models.ForeignKey(Share, related_name='+')


# If user unsubscribes from an item, they will not receive notifications of comments on that item
class UnsubscribeItem(models.Model):
    user = models.ForeignKey(User, related_name='+')
    item = models.ForeignKey(Item, related_name='+')


class Comment(models.Model):
    item = models.ForeignKey(Item, related_name='comments')
    user = models.ForeignKey(User, related_name='+')
    comment = models.TextField()

如果我想获得一个用户的所有通知,我可以简单地查询Notification表。但是,如果用户取消订阅了任何CommentNotification条目(仅当存在UnsubscribeItemuser=request.useritem=comment.item的条目时),我还想排除这些条目。你知道吗

当然,问题是我要筛选的字段不在基类上。是否可以修改查询集本身以排除这些条目?或者在序列化集合时是否需要排除它们?(如果有帮助的话,我将使用django rest框架为我的API序列化。)


Tags: tonamemodelmodelstypetablecomment条目