Issue
I need to concateanate serialized models with custom field = list[]
I have a user_profile model and I want to know if particular user is "mine(active user's)" friend, in the users list (list_boolean = ["True", "False", "True"])
views.py:
class User_profile_view(APIView):
def get(self, request):
#this is example list which i need to link
list_boolean = ["True", "False", "True"]
query = User_profile.objects.all()
serializer_class = User_profile_serializer(query, many=True)
return Response(serializer_class.data)
models.py:
class User_profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
age = models.CharField(max_length=100)
city = models.CharField(max_length=100)
serializer.py:
class User_profile_serializer(serializers.ModelSerializer):
class Meta:
model = User_profile
exclude = ["id"]
Is there any way to link particular list, to objects? it might be inside of the object (which is better) or outside.
Solution
You can use a SerializerMethodField to add this information.
class User_profile_serializer(serializers.ModelSerializer):
class Meta:
model = User_profile
exclude = ["id"]
is_friend = serializers.SerializerMethodField()
def get_is_friend(self, ob):
#some query to determine if the user in question (ob) is a friend with the current user (self.context['current_user'])
return True/False
Answered By - iri
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.