SilentDev
SilentDev

Reputation: 22747

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"?

Upvotes: 9

Views: 7760

Answers (2)

Nzechi Nwaokoro
Nzechi Nwaokoro

Reputation: 19

Fields completely deal with django's ORM and attributes are regular class variables that are used to hold the state of a particular instance of a class.

Upvotes: 0

Rod Xavier
Rod Xavier

Reputation: 4043

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.

Upvotes: 25

Related Questions