简体   繁体   中英

How to add a model field calculated by data from to other model?

I have the following models:

# 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)
class TestViewset(viewsets.ModelViewSet):
    serializer_class = TestSerializers
    permission_classes = (permissions.IsAuthenticated,)

    def get_queryset(self):
        if self.request.user.is_superuser:
            return Test.objects.all()
        else:
            return Test.objects.filter(author=self.request.user)

So each test can be made by many testers.

My wish is to count how many testers conducted the test , ie when I do a GET request to the TestViewset I wish to get in addition to current fields [name, author] a count field , for each test which specify how many testers have been tested.

Appreciate the help!

You can annotate count on view level:

from django.db.models import Count

def get_queryset(self):
    if self.request.user.is_superuser:
        return Test.objects.all().annotate(count=Count("tester"))

And on serializer level you can use SerializerMethodField to render this value:

class TestSerializers:
    count = serializers.SerializerMethodField()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM