Django - Creating an instance via the serializer with a foreign key reference

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Django - Creating an instance via the serializer with a foreign key reference



I have a agencies and users. I want to create User instances via the UserSerializer which have an agency_id. However the serializer's validated_data does not have the agency_id after calling is_valid().


User


UserSerializer


agency_id


validated_data


agency_id


is_valid()


class Agency(models.Model):
name = models.CharField(max_length=60)

class User(modes.Model):
username = models.CharField(max_length=60)
agency = models.ForeignKey(Agency, blank=True, null=True)

class UserSerializer(serializers.ModelSerializer):

class Meta:
User = get_user_model()
model = User

fields = ( 'id', 'username', 'agency_id' )

read_only_fields = ['id']



Try to create a user via the serializer which belongs to the Acme Agency:


agency = Agency.objects.create(name="Acme Agency")
serializer = UserSerializer(data= 'username':'wiley', 'agency_id': agency.id )

serializer.is_valid() # True
serializer.validated_data.get('agency_id') # None



Creating a user via the UserManager using the agency id works just fine:


user = User.objects.create(username='wiley', agency_id=1)
user.agency.id # 1





print serializer.data after serializer.is_valid() # True
– Hemanth SP
Aug 10 at 15:32




1 Answer
1



use agency instead of agency_id in UserSerializer as


agency


agency_id


class UserSerializer(serializers.ModelSerializer):
class Meta:
User = get_user_model()
model = User
fields = ('id', 'username', 'agency')
read_only_fields = ['id']



and use the serailizer as,


serializer = UserSerializer(data= 'username':'wiley', 'agency': agency.id )





That works great! I expected the field names to mimic those of underlying object...
– Codewise
Aug 10 at 20:15






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard