1👍
First of all, the data format is not in the post request is wrong:
it supposed to be following:
{"allergies": [{"name": "Beef"},{"name": "Pork"}]}
Now let’s modify your def create()
inside your serializer
def create(self, validated_data):
allergies_data =validated_data.pop('allergies', [])
names = [allergy.get('name') for allergy in allergies_data if allergy]
al = IngFamily.objects.filter(name__in=names) # using names(list) for filtering by __in
user1 = UserProfile.objects.create(**validated_data)
user1.allergies.add(*al) # notice there have * before "al" (as we are putting list inside add()
# user1.save() # we don't need to call `save()` as we are updating ManyToMany field.
return user1
1👍
You should but .save()
inside loop and edit your query to be like:
def create(self, validated_data):
allergies_data =validated_data.pop('allergies', [])
user1=UserProfile.objects.create(**validated_data)
for allergy in allergies_data:
al=IngFamily.objects.get(name=allergy['name'])
user1.allergies.add(al)
#here you should add it
user1.save()
- Django – Extending another apps ModelAdmin?
- Variable not found. Declare it as envvar or define a default value
0👍
Couple of things can be tried :
- It might be possible your database dont have some of the allergies coming in with user data. Thats why your al is coming empty.
- saving user data before you add allergies to it. This is important.
- By using ipdb or pdb, try to understand in what data form ‘allergy’ and ‘allergies_data’ is coming out. If indeed it is what you have written, there is no reason the following code shouldnt work.
def create(self, validated_data):
allergies_data =validated_data.pop('allergies')
user1=UserProfile.objects.create(**validated_data)
user1.save()
for allergy in allergies_data:
al=IngFamily.objects.get_or_create(name=allergy['name'])
user1.allergies.add(al)
return user1
0👍
Use something like:
class ProjectSerializer(serializers.ModelSerializer):
tag= serializers.StringRelatedField(many=True)
class Meta:
model = Song
fields = '__all__'
Here is a reference doc – https://www.django-rest-framework.org/api-guide/relations/
Source:stackexchange.com