Home > Back-end >  queryset get data of the foreign key
queryset get data of the foreign key

Time:10-15

I have 2 models ( Users and Posts )

class Users(models.Model):
    email = models.CharField(max_length=225)


class Posts(models.Model):
    user = models.ForeignKey(Users, on_delete=models.CASCADE, default=1)
    type = models.TextField()

I want to include the user email when getting all posts. I have done the following but am only getting the user id.

class PostsViewSet(viewsets.ModelViewSet):
    serializer_class = PostsSerializer
    def get_queryset(self):
        queryset = Posts.objects.all()
        return queryset

How can I achieve to get the user email within the queryset ?

CodePudding user response:

use https://docs.djangoproject.com/en/4.1/ref/models/querysets/#prefetch-related (not strictly needed, but a good habit) to grab it from the database, use post.user.email to grab the value in code. i.e:

class PostsViewSet(viewsets.ModelViewSet):
    serializer_class = PostsSerializer
    queryset = Posts.objects.all().prefetch_related("user")


class PostsSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(source="user.email")
    ...

CodePudding user response:

You can annotate the field in the queryset:

from django.db.models import F

class PostsViewSet(viewsets.ModelViewSet):
    serializer_class = PostsSerializer
    def get_queryset(self):
        queryset = Posts.objects.annotate(user_email=F('user__email'))
        return queryset

CodePudding user response:

Use all power of serializers. https://www.django-rest-framework.org/api-guide/serializers/

class PostsViewSet(viewsets.ModelViewSet):
    serializer_class = PostsSerializer
    queryset = Posts.objects.all().prefetch_related("user")

class UserSerializer(serializers.ModelSerializer):
    class Meta:
         model = User
         fields = ('email')

class PostsSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    
    class Meta:
         model = Post
         fields = ('type', 'user')
         depth = 1
  • Related