gpt4 book ai didi

python - 如何使用 Django Rest Framework 将数据添加到 ManyToMany 字段?

转载 作者:太空狗 更新时间:2023-10-30 01:37:56 26 4
gpt4 key购买 nike

我是 DJango 的新手,我希望使用来自 rest 框架的序列化程序将数据添加到多对多字段。

我的模型:

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)

我的 Post 请求看起来像这样:

{"allergies": [{"name": ["Beef"]},{"name": ["Pork"]}]}

我已经坚持了一段时间,任何帮助将不胜感激:)

最佳答案

首先是不是post请求中的数据格式不对:

它应该如下:

{"allergies": [{"name": "Beef"},{"name": "Pork"}]}

现在让我们在序列化程序中修改 def create()

 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

关于python - 如何使用 Django Rest Framework 将数据添加到 ManyToMany 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30554241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com