How To Include In Queryset Details Fields Of A Foreign Key (django And Rest_api)
I use rest_api in django in order to display a queryset of 'chats'. I tried to get it done for a while, without success... in angularjs controller I call a function which do the fo
Solution 1:
You can make a property on your model:
classMessage(models.Model):# some code...@propertydefsender_name(self):
returnself.sender.name # username or whatever
Then is you serializer you create a custom field:
classChatsSerializer(serializers.ModelSerializer):
# some code...
sender_name = serializers.Field(source = 'sender_name') # source = 'name of property or method' you dont have to pass it inthis example becouse model property has the same name asthis serializer attribute
classMeta:
fields = ('sender_name', 'id', 'sender', 'recipient','thread','subject','moderation_reason','body')
Now you have an 'sender_name' object in your JSON response.
That's just one method I hope it helps :)
The second one is to add an UserModelSerializer:
classUserModelSerializer(serializers.ModelSerializer):
classMeta:
model = get_user_model()
classChatsSerializer(serializers.ModelSerializer):
# some code...
sender = UserModelSerializer()
recipient = UserModelSerializer()
classMeta:
fields = ('sender_name', 'id', 'sender', 'recipient','thread','subject','moderation_reason','body')
Retriving is ok. But creating and updating with it is a hard piece of coding.
You can always create an Angular service for your 'sender' object and after reciving your chat messages with only foreign keys, request data from a 'UserModelView' with those 'FK' and bind them together. That's a third method.
Post a Comment for "How To Include In Queryset Details Fields Of A Foreign Key (django And Rest_api)"