I have 3 models: Post
, Topic
, PostTopic
. PostTopic
contains all the topics related to the Post
. The models look like this:
class Topic(models.Model):
name = models.CharField(max_length=25, unique=True)
def save(self, *args, **kwargs):
topic = Topic.objects.filter(name=self.name)
if topic:
return topic[0].id
super(Topic, self).save(*args, **kwargs)
return self.id
class PostTopic(models.Model):
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
post= models.ForeignKey(Post, on_delete=models.CASCADE)
The Topic
model cannot have 2 topics that are the same. Here's how my serializer looks like:
class PostSerializer(serializers.ModelSerializer):
topics = serializers.ListField(
child=serializers.CharField(max_length=256), max_length=3
)
class Meta:
model = Post
fields = ('user', 'status', 'topics')
def create(self, validated_data):
topics= validated_data.pop('topics')
post = Post.objects.create(**validated_data)
for topic in topics:
topic_id = Topic(name=topic).save()
PostTopic(post_id=post.id, topic_id=topic_id).save()
return post
However, I get an error saying:
Got AttributeError when attempting to get a value for field
topics
on serializerPostSerializer
. The serializer field might be named incorrectly and not match any attribute or key on thePost
instance.
I understand what I'm doing wrong, but I'm not sure how I can fix it where I can save the topic in PostTopic
too. Is there a better way to do this?