Django how to create child record with parent id


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',

Below is my

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

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, 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.

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

>Solution :

Add user to your AccountSerializer.Meta.fields section

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = (

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

Leave a ReplyCancel reply