I am using a property decorator for a field and have put that field into the serializer meta class but keeps getting that error. I am not sure what is the issue.
My models:
class Example(models.Model):
creator = models.ForeignKey(
User,
on_delete=models.CASCADE,
null=True,
related_name="example"
)
@property
def example_packages(self):
return self.package.all()
class Package(models.Model):
parent = models.ForeignKey(
Example,
on_delete=models.CASCADE,
null= True,
related_name="package"
)
name = models.CharField(max_length=25,blank=True)
My serializers:
class ExampleSerializer(serializers.ModelSerializer):
class Meta:
model = Example
fields = ['id','creator','example_packages']
The error that I keep geeting is that example_packages is not Json serializable.
CodePudding user response:
class PackageSerializer(serializers.ModelSerializer):
class Meta:
model = Package
fields = ['id','name']
class ExampleSerializer(serializers.ModelSerializer):
package = PackageSerializer(many=True)
class Meta:
model = Example
fields = ['id','creator','package']
CodePudding user response:
If the @property needs to be in 'Example'
class Example(models.Model):
creator = models.ForeignKey(
User,
on_delete=models.CASCADE,
null=True,
related_name="example"
)
@property
def example_packages(self):
return self.package.all()
class Package(models.Model):
parent = models.ForeignKey(
Example,
on_delete=models.CASCADE,
null= True,
related_name="package"
)
name = models.CharField(max_length=25,blank=True)
The serializer should look like:
class ExampleSerializer(serializers.ModelSerializer):
example_packages = serializers.CharField()
class Meta:
model = Example
fields = ['id','creator','example_packages']