I have following serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id']
class PersonSerializer(serializers.ModelSerializer):
user = UserSerializer()
comments = CommentSerializer(source='comment_set', many=True)
class Meta:
model = Person
fields = '__all__'
And related views
class PersonRetrieveView(generics.RetrieveAPIView):
queryset = Person.objects.all()
serializer_class = PersonSerializer
class UserRetrieveView(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (permissions.IsAuthenticated, )
The models are standard, Person related to User by Foreign key.
So my url path('persons/<int:pk>/', PersonRetrieveView.as_view()),
returns Person object with user field with user id. I want to make kinda reverse logic. By user id I want to query all users with field person with all persons related to this user by user id.
I can't just make
class UserSerializer(serializers.ModelSerializer):
person = PersonSerializer()
class Meta:
model = User
fields = ['id']
because Person serializer defined below the User serializer. Is there any way to do it simple with generics?
Your models.py should look like this:
class Person(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='persons', # This is important
on_delete=models.CASCADE
)
# Other fields...
Then serializers.py:
class PersonSerializer(serializers.ModelSerializer):
persons=serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = Person
For more info or other relation types you can look at the DRF doc: https://www.django-rest-framework.org/api-guide/relations/