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"?
Asked
Active
Viewed 7,301 times
2 Answers
25
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
.

Rod Xavier
- 3,983
- 1
- 29
- 41
-
7You mentioned that "a model attribute pertains to a method or property that is added to a model". Is there any way of creating a model attribute without the `@property` decorator? In your example, you used the `@property` decorator for `description` but not for `compute_total` but you mentioned that `compute_total` is also a model attribute.. With that said, is the `@property` decorator needed? What purpose does it serve? – SilentDev Oct 30 '15 at 00:27
-
10The `@property` decorator is not needed. When you add the decorator it becomes an object property which means you can't pass arguments when calling it. So for the above you call `description` like `obj.description`. Meanwhile, `compute_total` is a method, which means that you can add/pass arguments when calling it. You call `compute_total` like `obj.compute_total()` or if there are arguments, `obj.compute_total(arg1, arg2, kwarg1=val1)` – Rod Xavier Oct 30 '15 at 00:31
-
When would you want to use `model_attributes`? And how would you make the determination between using a model attribute vs doing something via `annotate` on the query set? (2 weeks into Python/Django here, so I have lots of questions) – Snekse Jun 29 '18 at 15:14
-
it's also helpful to keep in mind that attributes (those using the `@property` decorator) cannot be filtered using django's queryset API while `fields` can because fields map to database columns. https://stackoverflow.com/questions/1205375/filter-by-property – Deven Aug 21 '18 at 11:12
0
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.

Nzechi Nwaokoro
- 19
- 2