Custom field with special constrains in DRF serializer

Viewed 34

I'm trying to add a custom field with some special constrains in DRF serializer. Following are 2 sample models:

class ModelA(models.Model):
    field1 = models.CharField(max_length=200)
    field2 = models.CharField(max_length=200)
    field3 = models.CharField(max_length=200)
    
class ModelB(models.Model):
    field4 = models.ForeignKey(ModelA, on_delete=models.CASCADE)
    field5 = models.CharField(max_length=200)

What I want is a serializer based on ModelA, but with a custom field displaying a string combining field5s of all ModelB instances this ModelA instance has.

I know this API design is a little bit weird, but based on the existing code base, we have to do it this way.

Also I wanna this field to be writable, so SerializerMethodField doesn't work. I tried to follow the example here.

But my case is a little bit different, since it involves multiple models. Some sample code would be very helpful! Thx!

0 Answers
Related