Kadir Akın
Kadir Akın

Reputation: 43

How can i handle django nested models?

I have a User, Post and Tag model in Django. Tag model is not relevant for this topic. I can get all the data to the front end with nested objects. In the other hand when i want to create a new post i send the post data to django and in django view i am trying to update the data with relating the logged user to the "Post" but when i do that it gives me;

  {'owner': {'username': [ErrorDetail(string='A user with that username already exists.', code='unique')]}}

error. How can i solve this error ?

models.py;

class Post(models.Model):
  # Post specs
  title = models.CharField(max_length=100, null=False)
  place = models.CharField(max_length=100, null=False)
  notes = models.CharField(max_length=10000, null=False)
  tags = models.ManyToManyField(Tag)
  start_date = models.DateField(null=True)
  end_date = models.DateField(null=True)
  created_at = models.DateField(auto_now=True)
  owner = models.ForeignKey(User , null = True, on_delete=models.SET_NULL) 

serializers.py;

class PostSerializer(serializers.ModelSerializer):
  tags = serializers.SlugRelatedField(
        many=True,
        queryset=Tag.objects.all(),
        slug_field='name'
     )
  owner = UserSerializer()
  class Meta:
    model = Post
    fields = ('title','place','notes','start_date','end_date','created_at','id','owner','tags')

By the way if i change serializer.py like owner = UserSerializer it gives just primary key value. In front end i cant to anything with a integer number and i dont want to make an another api call for user model. Lastly view post function;

  def post(self, request, format =None):
    """
    Creates a post
    """
    post = request.data                          ## copy dictionary to a variable
    authenticatedUserDataAsDict =  request.user.__class__.objects.filter(pk=request.user.id).values().first()
    post.update( {'owner': authenticatedUserDataAsDict} )        ## attach authenticated user to post end
    serializer = PostSerializer(data = post)      ## serialize the dict
    if serializer.is_valid():
      serializer.save()                           ## if data valid save it.
      return Response(serializer.data, status = status.HTTP_201_CREATED)
    print("not valid->",serializer.errors)
    return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) # if it's not raise http 400

Upvotes: 2

Views: 7386

Answers (1)

Kadir Akın
Kadir Akın

Reputation: 43

SOLVED

Hi again, it seems that rest framework have no idea about our request(create or get wise) because we are dealing with nested serializers. So i found this article in medium and it helped me to solve my problem.

Upvotes: 2

Related Questions