Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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',
                         on_delete=models.CASCADE)

Below is my serializers.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading