Reputation: 75
I want to tag users in an image and save it, I used nested serializer since you can tag more than one user in an image. The problem is that the image is saved without the tags(they are none). Here is the codes: models.py
class TagUsername(models.Model):
# the tag is person
tag = models.ManyToManyField(User, related_name='tag_username')
image = models.ForeignKey(Image)
# # De tection Rectangle specs(width,height, coordinate x & coordinate y)
# width = models.FloatField()
# length = models.FloatField()
# xCoordinate = models.FloatField()
# yCoordinate = models.FloatField()
# who added this tag
user = models.ForeignKey(User, on_delete=models.CASCADE)
serializers.py
class TagUsernameSerializer(serializers.ModelSerializer):
tag = UsernameTagSerializer(read_only=True, many=True)
user = serializers.SlugRelatedField(queryset=User.objects.all(), slug_field="username")
image = serializers.CharField(source='image_id')
class Meta:
model = TagUsername
fields = ('tag', 'user', 'image')
UsernameTagSerializer:
class UsernameTagSerializer(serializers.ModelSerializer):
# username = serializers.SlugRelatedField(queryset=User.objects.all(), slug_field="username")
class Meta:
model = User
# fields I want only
fields = ('username', )
Any idea whats wrong !
Upvotes: 1
Views: 537
Reputation: 47354
You need to override create
method to save nested objects. Try this:
def create(self, validated_data):
tag_username = super().create(validated_data)
for tag in validated_data['tag']:
user = User.objects.get(username=tag['username']
tag_username.tag.add(user)
return tag_username
You can find more details about writable nested serialization in docs.
Upvotes: 1