Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - what's the difference between a model field and a model attribute?

In this link (for the ReadOnlyField): http://www.django-rest-framework.org/api-guide/fields/#readonlyfield it says "This field is used by default with ModelSerializer when including field names that relate to an attribute rather than a model field". With that said, can you give me an example of a Model field name that is an "attribute" and a Model field name that is a "field"?

like image 297
SilentDev Avatar asked Oct 27 '15 22:10

SilentDev


1 Answers

In Django, a model field pertains to a column in the database. On the other hand, a model attribute pertains to a method or property that is added to a model.

Example

class MyModel(models.Model):
    name = models.CharField()
    quantity = models.IntegerField()
    price = models.DecimalField()

    @property
    def description(self):
        return '{}x of {}'.format(quantity, name)

    def compute_total(self):
        return quantity * price

In the example above, name, quantity and price are model fields since they are columns in the database. Meanwhile, description and compute_total are model attributes.

like image 107
Rod Xavier Avatar answered Oct 14 '22 19:10

Rod Xavier