我有一个模型,用于定义可以附加到事件的类别。我通过直通模型在事件中添加/删除类别时进行跟踪。
class ZCategory(models.Model):
name = models.CharField(max_length=8)
class ZCategoryInstanceThrough(models.Model):
category = models.ForeignKey('events.ZCategory')
event = models.ForeignKey('events.GenericModel', related_name="eventcatinstances")
added_by = models.ForeignKey('common.User', related_name="eventcatadds")
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
date_removed = models.DateTimeField(null=True, blank=True) # aka 'deleted'
class GenericModel(models.Model):
data_zs = models.ManyToManyField('ZCategory', through=ZCategoryInstanceThrough, blank=True)
当我在带有.values()的实例化GenericModel Queryset上调用data_zs时,默认情况下我不希望没有任何项目,其中date_removed没有被删除。
有直接的方法吗?
编辑 - 示例查询
self.eventcatinstances.filter(**filter_args).values('data_zs').annotate(count=Count('data_zs'))
答案 0 :(得分:0)
试试这个:
self.eventcatinstances.filter(data_zs__date_removed__isnull=True).values('data_zs').annotate(count=Count('data_zs'))
修改强>
你得到同样的错误吗?
GenericModel.objects.filter(data_zs__date_removed__isnull=True).values('data_zs').annotate(count=Count('data_zs'))
修改2
如果您在过滤器中使用zcategoryinstancethrough作为起点呢?
GenericModel.objects.filter(zcategoryinstancethrough__date_removed__isnull=True).values('data_zs').annotate(count=Count('data_zs'))
或者
self.eventcatinstances.filter(zcategoryinstancethrough__date_removed__isnull=True).values('data_zs').annotate(count=Count('data_zs'))
答案 1 :(得分:0)
经过进一步的反复试验后,我意识到答案在整个时间里都是如此。
self.eventcatinstances.filter(
zcategoryinstancethrough__date_removed__isnull=True
zcategoryinstancethrough__isnull=False
).values(
'zcategoryinstancethrough__category'
).annotate(
count=Count('zcategoryinstancethrough__category')
)