gpt4 book ai didi

python - 为什么我没有获得附加到我的问题实例的标签实例?

转载 作者:太空宇宙 更新时间:2023-11-03 20:35:04 25 4
gpt4 key购买 nike

我是 django 的初学者,也是 DRF 的新手。所以,问题出在我的嵌套序列化器中的 create() 方法中。问题是它创建了新的标签实例,但不将它们附加到我想在 POST 请求中发送到服务器上的问题实例。

这是我的模型:

class Question(models.Model):
title = models.CharField(max_length=100)
content = models.CharField(max_length=500, default="Write your question") # HTMLField() look TinyMCE
tags = models.ManyToManyField("Tag")
pub_date = models.DateField(auto_now=False, auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
answers = models.ManyToManyField("Answer")
comment_cnt = models.IntegerField(default=0)
like_cnt = models.IntegerField(default=0)
def __str__(self):
return self.title

def get_absolute_url(self):
return reverse('questions', args=[self.title])

class Meta:
ordering = ['pub_date']

class Answer(models.Model):
content = models.CharField(max_length=500, default="Write the answer") # HTMLField() look TinyMCE
pub_date = models.DateField(auto_now=False, auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
like_cnt = models.IntegerField(default=0)
def __str__(self):
return self.author.username

class Tag(models.Model):
name = models.CharField(max_length=50)
discription = models.CharField(max_length=500, default="This is description")
use_cnt = models.IntegerField(default=0)
def __str__(self):
return self.name

这是序列化器:

class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = '__all__'
read_only_fields = ['use_cnt']

class AnswerSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = '__all__'

class QuestionSerializer(serializers.ModelSerializer):
tags = TagSerializer(many=True )
answers = AnswerSerializer(many=True, read_only=True)

class Meta:
model = Question
fields = '__all__'

def create(self, validated_data):
tags_data = validated_data.pop('tags')
question = Question.objects.create(**validated_data)
for tag_data in tags_data:
Tag.objects.create(question=question, **tag_data)
return question

这是我的观点:

class QuestionList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):

queryset = Question.objects.all()
serializer_class = QuestionSerializer
# permission_classes = [AllowAny]

def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)

def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)

class QuestionDetail(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):

queryset = Question.objects.all()
serializer_class = QuestionSerializer
# permission_classes = [IsOwnerOrReadOnly]
lookup_field = 'title'

def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)

def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)

def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)

class TagList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):

queryset = Tag.objects.all()
serializer_class = TagSerializer
# permission_classes = [AllowAny]

def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)

def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)

我在我的 POST 请求中发送此内容:

{
"tags": [{
"name": "new tag",
"discription": "description"
},
{
"name": "another tag",
"discription": "description"
}],
"title": "new one",
"content": "new content",
"comment_cnt": 2,
"like_cnt": 2,
"author": 2
}

并收到此信息:

"id": 14,
"tags": [],
"answers": [],
"title": "new one",
"content": "new content",
"pub_date": "2019-07-26",
"comment_cnt": 2,
"like_cnt": 2,
"author": 2

分别标记:

{
"id": 9,
"name": "new tag",
"discription": "description",
"use_cnt": 0
},
{
"id": 10,
"name": "another tag",
"discription": "description",
"use_cnt": 0
}

提前致谢!

最佳答案

您的标记模型没有问题,因此它不会按您的预期工作。

尝试这样做:

   def create(self, validated_data):
tags_data = validated_data.pop('tags')
question = Question.objects.create(**validated_data)
for tag_data in tags_data:
tag = Tag.objects.create(**tag_data)
question.tags.add(tag)

question.save()

return question

关于python - 为什么我没有获得附加到我的问题实例的标签实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57218101/

25 4 0