【发布时间】:2022-01-02 07:10:40
【问题描述】:
我有一个用于注释的 django 应用程序,我通过多对多关系将有关图像注释的信息保存到模型 BiomarkerAnnotations 中。我使用annotated 字段跟踪哪些用户完成了图像注释。
from django.contrib.auth.models import User
class Biomarker(models.Model):
name = models.CharField(max_length=256)
description = models.CharField(max_length=1024)
class Image(models.Model):
number = models.IntegerField(default=0)
absolute_path = models.CharField(max_length=2560)
biomarkers = models.ManyToManyField(Biomarker, through='BiomarkerAnnotations', related_name="biomarker_annotations")
annotated = models.ManyToManyField(User, related_name="annotated_by")
class BiomarkerAnnotations(models.Model):
_image = models.ForeignKey(Image, on_delete=models.CASCADE)
biomarker = models.ForeignKey(Biomarker, on_delete=models.CASCADE)
user = models.ForeignKey(User, null=True,on_delete=models.SET_DEFAULT, default=1)
我想创建一个视图,为特定用户(发送请求的用户)返回他已注释的图像数量以及还有多少图像需要注释。到目前为止,我已经达到了这一点,但它似乎不起作用:查询返回的总计数大于图像计数。
class AnnotStatsSerializer(serializers.ModelSerializer):
annotations = serializers.IntegerField()
count = serializers.IntegerField()
class Meta:
model = Image
fields = ("count", "annotations")
class AnnotatedStatsViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Image.objects.all()
serializer_class = AnnotStatsSerializer
def get_queryset(self):
queryset = self.queryset
user_object = self.request.user
project_id = self.request.query_params.get('project', None)
if project_id is None: raise Http404
queryset = queryset.annotate(annotations=Case(When(annotated__id__exact=user_object.id, then=Value(1)), default=Value(0), output_field=IntegerField())) \
.values('annotations').annotate(count=Count('annotations')).order_by('annotations') \
.values('count', 'annotations')
return queryset
任何帮助表示赞赏。
【问题讨论】:
-
我不清楚为什么你的
Image模型中有两个ManyToManyFields。 -
用户可能在未完全完成注释的情况下使用一些生物标记对图像进行了注释。如果用户对象是
annotated字段的一部分,则不会将图像提供给用户进行注释。否则它将是并且biomarkers注释预先填充了 biomarkers 字段的内容。对于这个问题,我会对完整的注释感兴趣,即annotated -
你见过
infield lookup吗?另请参阅此答案stackoverflow.com/a/4508083/6143954。