Django使用多表继承过滤查询

时间:2016-03-03 13:23:31

标签: python django

我正在使用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-framework为我的API序列化,如果有帮助的话。)

0 个答案:

没有答案