Django通用外键反向滤波器

时间:2015-09-17 18:12:36

标签: django generic-foreign-key

我有一个名为"评论"它使用通用外键:

class CommentManager(models.Manager):

    def for_model(self, model):
        """
        QuerySet for all comments for a particular model (either an instance or
        a class).
        """
        ct = ContentType.objects.get_for_model(model)
        qs = self.get_query_set().filter(content_type=ct)
        if isinstance(model, models.Model):
            qs = qs.filter(object_pk=force_text(model._get_pk_val()))
        return qs


class Comment(models.Model):
    """
    A user comment about some object.
    """
    status = models.CharField(max_length=12, blank=True, null=True)
    sub_status = models.CharField(max_length=500, blank=True, null=True)
    comment = models.TextField()

    content_type = models.ForeignKey(
        ContentType,
        verbose_name=_('content type'),
        related_name="content_type_set_for_%(class)s")
    object_pk = models.TextField(_('object ID'))
    content_object = generic.GenericForeignKey(ct_field="content_type",
                                               fk_field="object_pk")

您可以发表评论的一件事是Tickets

class Ticket(CommonModel):
    type = models.ForeignKey(TicketType)
    priority = models.PositiveSmallIntegerField()
    status = models.ForeignKey(TicketStatus)
    access_serial_number = models.PositiveSmallIntegerField(null=True)
    parent = models.ForeignKey('self', null=True, related_name='child')
    submitted = models.DateTimeField()

我对Tickets进行了大量过滤 - 过去我对门票的评论所做的就是当我显示Ticket时,我使用Comments.objects.for_model(ticket)来查找所有评论为了它。但现在我要做的是找到在评论中有特定文字的Tickets。没有comment_set或等效GenericForeignKey

这就是我提出的,但它非常可怕:

comment_ticket_ids = [int(c.object_pk) for c in Comment.objects.for_model(Ticket).filter(comment__icontains='error')]
tickets = Ticket.filter(status=open_status, id__in=comment_ticket_ids)

必须有更好的方法。

1 个答案:

答案 0 :(得分:0)

也许您可以使用.extra()添加内容来提供帮助。而不是

comment_ticket_ids = [int(c.object_pk) for c in Comment.objects.for_model(Ticket).filter(comment__icontains='error')]
tickets = Ticket.filter(status=open_status, id__in=comment_ticket_ids)

您可以附加字段id_wanted

extra_select = {
 'id_wanted': 'CASE WHEN (SELECT COUNT(*) FROM tickets WHERE comments something) > 0 THEN TRUE ELSE FALSE END'
}

然后使用额外选择过滤门票:

tickets = Tickets.objects.filter(ticket__status=open_status, id_wanted__isnull=False).extra(extra_select)

我不完全清楚为什么你不能在这两个模型之间建立FKey关系。