Ad

Property Method And Other Methods In Django Models

I have been using the property method every now and then and understand its uses. It basically acts the same as the field but without actually creating a column in db, and can be easily accessed within the serializer as model fields. But how can the other methods be accessed just like this baby_boomer function of Person model here below? How can it be accessed in serializer and also in the views or queryset??

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birth_date = models.DateField()

    def baby_boomer_status(self):
        "Returns the person's baby-boomer status."
        import datetime
        if self.birth_date < datetime.date(1945, 8, 1):
            return "Pre-boomer"
        elif self.birth_date < datetime.date(1965, 1, 1):
            return "Baby boomer"
        else:
            return "Post-boomer"

    @property
    def full_name(self):
        "Returns the person's full name."
        return '%s %s' % (self.first_name, self.last_name)
Ad

Answer

Pass the source parameter to a serializer field to access a method on the model, the method must take only a single self parameter

class PersonSerializer(serializers.ModelSerializer):

    foo = serializers.CharField(source='baby_boomer_status', read_only=True)

    class Meta:
        model = Person
        fields = ['field_a', 'field_b']
Ad
source: stackoverflow.com
Ad