我正在尝试在创建帖子时保存多个标签字段。
这是我发布新帖子的帖子
{
"name":"testpost1",
"caption":"test caption n",
"tags":[{"name":"tag1"}]
}
模型
class Tags(models.Model):
id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
name = models.CharField(max_length=50, unique=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="created_tags")
time_created = models.DateTimeField(auto_now_add=True)
followers = models.ManyToManyField(User, related_name="following_tags")
posts = models.ManyToManyField('Posts', related_name='tags', symmetrical=True)
class Posts(models.Model):
id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
name = models.CharField(max_length=50)
caption = models.TextField(max_length=1000)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
Post和tag
的序列化程序class TagsSerializerMini(serializers.ModelSerializer):
class Meta:
model = Tags
fields = ('name', )
class PostsSerializer(QueryFieldsMixin, serializers.ModelSerializer):
created_by = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
tags = TagsSerializerMini(many=True, required=False)
class Meta:
model = Posts
fields = ('id', 'name', 'caption', 'tags', 'num_reactions', 'num_comments', 'created_by', 'posted_time',
'updated_time', )
read_only_fields = ('id', 'posted_time', 'updated_time', )
def create(self, validated_data):
tags_data = validated_data.pop('tags', [])
post = Posts.objects.create(**validated_data)
for tag in tags_data:
t, _ = Tags.objects.get_or_create(name=tag["name"], created_by=self.context['request'].user)
t.posts.add(post)
return post
现在的问题是,当我向帖子t.posts.add(post)
添加帖子时,它会抛出错误django.db.utils.IntegrityError: FOREIGN KEY constraint failed
。我也尝试从shell中添加一个帖子,它给出了同样的错误。
答案 0 :(得分:1)
我遇到了类似的问题,并通过使用中介模型(使用through
)解决了此问题,这是代码的外观:
models.py:
class Tags(models.Model):
# ...
posts = models.ManyToManyField('Posts', related_name='tags', symmetrical=True, through='PostsTag')
class PostTag(models.Model):
tag = models.ForeignKey(Tags)
post = models.ForeignKey(Posts)
序列化器:
# ...
def create(self, validated_data):
tags_data = validated_data.pop('tags', [])
post = Posts.objects.create(**validated_data)
for tag in tags_data:
t, _ = Tags.objects.get_or_create(name=tag["name"], created_by=self.context['request'].user)
PostTag.objects.create(tag=t, post=post) # <----- Create m2m relation
return post
注意:我没有测试代码,但是希望这会有所帮助!