我有一个名为"Comments"的模型,它使用一个通用的外键:
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)
一定有更好的办法。
也许您可以使用.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'
}
然后用额外的select:
过滤门票tickets = Tickets.objects.filter(ticket__status=open_status, id_wanted__isnull=False).extra(extra_select)
我不太清楚为什么这两个模型之间不能有FKey关系