Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将由中的数据计算的模型字段添加到其他模型?_Python_Django_Django Rest Framework - Fatal编程技术网

Python 如何将由中的数据计算的模型字段添加到其他模型?

Python 如何将由中的数据计算的模型字段添加到其他模型?,python,django,django-rest-framework,Python,Django,Django Rest Framework,我有以下型号: # models.py class Test(models.Model): name = models.CharField(max_length=40) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Tester(models.Model): test_id = models.ForeignKey(Test, on_delete=m

我有以下型号:

# models.py
class Test(models.Model):
    name = models.CharField(max_length=40)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

class Tester(models.Model):
    test_id = models.ForeignKey(Test, on_delete=models.DO_NOTHING)
因此,每个测试都可以由许多测试人员进行

我希望计算有多少测试人员进行了测试,即当我向
TestViewset
发出GET请求时,我希望在当前字段[姓名,作者]之外,为每个测试获取一个计数字段,该字段指定有多少测试人员进行了测试


谢谢你的帮助

您可以在视图级别上注释计数:

from django.db.models import Count

def get_queryset(self):
    if self.request.user.is_superuser:
        return Test.objects.all().annotate(count=Count("tester"))
在序列化程序级别,可以使用
SerializerMethodField
呈现此值:

class TestSerializers:
    count = serializers.SerializerMethodField()

    def get_count(self, obj):
        if hasattr(obj, "count"):
            return obj.count

@helpper
get\u queryset
应该像您的问题一样位于
TestViewset
类中。您只需将
.annotation(count=count(“tester”)
添加到queryset
tester
是需要从中计数的相关模型对象的大小写名称。它是检测仪型号中的
外键
的反向关系名称。请在此处查看详细信息:
class TestSerializers:
    count = serializers.SerializerMethodField()

    def get_count(self, obj):
        if hasattr(obj, "count"):
            return obj.count