Home > Back-end >  Django how to create child record with parent id
Django how to create child record with parent id

Time:10-02

I am trying to link the accounts table with the user table using the Foreigkey field.

Inside my model, I have Account class.

class Account(models.Model):
  account_number = models.CharField(max_length=30)
  account_type = models.CharField(max_length=20)
  user = models.ForeignKey(User, related_name='accounts',
                         on_delete=models.CASCADE)

Below is my serializers.py

class AccountSerializer(serializers.ModelSerializer):
  class Meta:
    model = Account
    fields = ('id', 'account_number',
              'account_type')

class UserSerializer(serializers.ModelSerializer):
  accounts = AccountSerializer(many=True) 
  class Meta:
    model = User
    fields = ('id', 'first_name', 'last_name',
              'email', 'password', 'accounts')
    extra_kwargs = {'password': {'write_only': True, 'required': True}}

In my view.py, I created AccountViewSet

class AccountViewSet(viewsets.ModelViewSet):
  queryset = Account.objects.all()
  serializer_class = AccountSerializer

I am trying to insert an account record with a user id using Postman, I am getting the following error message.

enter image description here

django.db.utils.IntegrityError: null value in column "user_id" of relation "app_account" violates not-null constraint DETAIL: Failing row contains (7, 0187898789, Saving, null).

I already have a user record with id 1 in the database, and in postman, I did pass the user_id. However, when I try to print the validated_data it doesn't show the user_id

CodePudding user response:

Add user to your AccountSerializer.Meta.fields section

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = (
            'id',
            'account_number',
            'account_type',
            'user'
        )

and now, use user instead of user_id while sending the payload

  • Related