Django ManyToMany Through Filter



我有一个模型,它定义了可以附加到事件的类别。我正在跟踪类别何时通过through模型添加/从事件中删除。

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'))

在进一步的尝试和错误之后,我意识到答案一直就在我面前。

self.eventcatinstances.filter(
    zcategoryinstancethrough__date_removed__isnull=True
    zcategoryinstancethrough__isnull=False
).values(
    'zcategoryinstancethrough__category'
).annotate(
    count=Count('zcategoryinstancethrough__category')
)

试试这个:

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'))

相关内容

  • 没有找到相关文章

最新更新