Django模型中的非数据库字段 [英] Non-database field in Django model

查看:372
本文介绍了Django模型中的非数据库字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在Django模型中有一个不能存储在数据库中的字段。

例如:

Is it possible to have a field in a Django model which does not get stored in the database.
For example:

class Book(models.Model):
    title = models.CharField(max_length=75)
    description models.CharField(max_length=255, blank=True)
    pages = models.IntegerField()
    none_db_field = ????

然后我可以做

book = Book.objects.get(pk=1)
book.none_db_field = 'some text...'
print book.none_db_field

感谢

推荐答案

只要您不希望该属性持久存在,我不明白为什么您无法创建像您所描述的属性。我实际上在某些模型上做同样的事情来确定哪些是可编辑的。

As long as you do not want the property to persist, I don't see why you can't create a property like you described. I actually do the same thing on certain models to determine which are editable.

class Email(EntryObj):
    ts = models.DateTimeField(auto_now_add=True)
    body = models.TextField(blank=True)
    user = models.ForeignKey(User, blank=True, null=True)
    editable = False
    ...


class Note(EntryObj):
    ts = models.DateTimeField(auto_now_add=True)
    note = models.TextField(blank=True)
    user = models.ForeignKey(User, blank=True, null=True)
    editable = True

这篇关于Django模型中的非数据库字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆