在此链接中(对于ReadOnlyField):http://www.django-rest-framework.org/api-guide/fields/#readonlyfield说:“当包含与属性而不是模型字段相关的字段名称时,默认情况下此字段与ModelSerializer一起使用”。这么说,您能给我一个示例字段名称为“属性”的示例字段名称为“字段”的示例吗?
最佳答案
在Django
中,model field
与数据库中的列有关。另一方面,model attribute
属于添加到model
的方法或属性。
例子
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
在上面的示例中,
name
,quantity
和price
是model fields
,因为它们是数据库中的列。同时,description
和compute_total
是model attributes
。
关于Django-模型字段和模型属性之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33379587/