I'm trying to serialize the User model from Django, including a manyToMany relation I created.
Here are my models:
class CompanyAccount(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
user_ids = models.ManyToManyField(User, through='CompanyUser')
class CompanyUser(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
user_id = models.ForeignKey(User, on_delete=models.CASCADE)
company_id = models.ForeignKey(CompanyAccount, on_delete=models.CASCADE)
is_company_admin = models.BooleanField(default=False, null=True)
Now my goal would be to get the company serialized and returned along with any user.
Here are my serializer, but sadly the company is not returned.
class CompanyAccountSerializer(serializers.ModelSerializer):
address_id = AddressSerializer(many=False)
class Meta:
model = CompanyAccount
fields = '__all__'
class UserSerializer(serializers.ModelSerializer):
company_id = CompanyAccountSerializer(many=False, read_only=True)
class Meta:
model = User
fields = ['id', 'username', 'email', 'first_name', 'last_name', 'company_id']
Any help is welcome :-)
CodePudding user response:
The default related name of a ManyToManyField
is modelname_set
, so you can implement this with:
class UserSerializer(serializers.ModelSerializer):
companyaccount_set = CompanyAccountSerializer(many=True, read_only=True)
class Meta:
model = User
fields = ['id', 'username', 'email', 'first_name', 'last_name', 'companyaccount_set']
If you want to rename the field, you can use:
class UserSerializer(serializers.ModelSerializer):
accounts = CompanyAccountSerializer(many=True, read_only=True, source='companyaccount_set')
class Meta:
model = User
fields = ['id', 'username', 'email', 'first_name', 'last_name', 'accounts']