I have end point for a post and the serializer that feeds that endpoint looks like this:
class PostSerializer(serializers.ModelSerializer):
images = PostImageSerializer(many=True, read_only=True, required=False)
uploaded_images = serializers.ListField(
required=False,
child=serializers.FileField(
allow_empty_file=False,
use_url=True,
),
write_only=True,
)
user_profile = ProfileSerializer(many=True, read_only=True)
class Meta:
model = Post
fields = [
"id",
"category",
"body",
"images",
"uploaded_images",
"video",
"can_view",
"can_comment",
"user",
"user_profile",
"published",
"pinned",
"created_at",
"updated_at",
]
def create(self, validated_data):
new_post = Post.objects.create(**validated_data)
images = dict((self.context["request"].FILES).lists()).get("files", None)
if images:
for image in images:
PostImage.objects.create(
image=image, post=new_post, user=validated_data["user"]
)
return new_post
and the data at the end point looks like this:
id 1
category 1
body "Hello how are you this is a post"
images
0
id 1
image "http://127.0.0.1:8000/storage/posts/post_1/0pxYb.jpg"
post 1
user 1
1
id 2
image "http://127.0.0.1:8000/storage/posts/post_1/12729465_237302183268986_1508875389_n.jpg"
post 1
user 1
2
id 3
image "http://127.0.0.1:8000/storage/posts/post_1/39342221_884539318417339_7097049967600074752_n.jpg"
post 1
user 1
3
id 4
image "http://127.0.0.1:8000/storage/posts/post_1/40024140_307464703336377_7213765493415477248_n.jpg"
post 1
user 1
video "http://127.0.0.1:8000/storage/user_1/posts/Beer.jpg"
can_view "Everybody"
can_comment "Everybody"
user 1
published true
pinned false
created_at "2022-12-11T10:16:31.784169Z"
updated_at "2022-12-11T10:16:31.784232Z"
The user has a profile and I need to get some of that profile data into this endpoint, but it’s not working for me. How can I get data from user profile into this end point please. I cannot find the answer in the DRF docs of how I can use a field value (user) in a serializer to get related data from another model (profile)