我对DJango来说相对较新,我希望使用其他框架中的序列化程序将数据添加到多对多字段中。
我的模特:
class IngFamily(models.Model):
name=models.CharField(max_length=30, unique=True, verbose_name='ingredient parent')
class UserProfile(models.Model):
user=models.ForeignKey(User)
allergies=models.ManyToManyField(IngFamily, verbose_name='allergies', null=True)
现在,我想使用其余的api将数据添加到UserProfile模型。
我环顾四周,但无处可寻。
到目前为止我所取得的成就:
串行器:
class IngFlySerializer(serializers.ModelSerializer):
class Meta:
model = IngFamily
fields= ('name',)
class UserProfileSerializer(serializers.ModelSerializer):
allergies=IngFlySerializer(many=True,)
class Meta:
model = UserProfile
fields=('allergies',)
def create(self, validated_data):
allergies_data =validated_data.pop('allergies', [])
#import pdb;pdb.set_trace()
user1=UserProfile.objects.create(**validated_data)
for allergy in allergies_data:
al=IngFamily.objects.filter(name=allergy.get('name'))
#al.name=allergy.get('name')
user1.allergies.add(al)
user1.save()
return user1
当我尝试使用它时," al"是空的。
视图:
class user_profile(generics.ListCreateAPIView):
serializer_class = UserProfileSerializer
permission_classes = (permissions.IsAuthenticated,)
def get_queryset(self):
user = self.request.user
return UserProfile.objects.filter(user=user)
def perform_create(self, serializer):
#import pdb; pdb.set_trace()
serializer.save(user=self.request.user)
class UserDetail(generics.RetrieveDestroyAPIView):
serializer_class = UserProfileSerializer
permission_classes = (permissions.IsAuthenticated,)
def get_queryset(self):
user1 = self.request.user
return UserProfile.objects.filter(user=user1)
我的帖子请求会看起来:
{"allergies": [{"name": ["Beef"]},{"name": ["Pork"]}]}
我已经坚持了一段时间,任何帮助都会受到赞赏:)
答案 0 :(得分:0)
可以尝试一些事情:
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