Django模型和Python属性 [英] Django models and Python properties

查看:79
本文介绍了Django模型和Python属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用python属性设置Django模型,像这样:

I've tried to set up a Django model with a python property, like so:

class Post(models.Model):
    _summary = models.TextField(blank=True)
    body = models.TextField()

    @property
    def summary(self):
        if self._summary:
            return self._summary
        else:
            return self.body

    @summary.setter
    def summary(self, value):
        self._summary = value

    @summary.deleter
    def summary(self):
        self._summary = ''

到目前为止,到目前为止还不错,在控制台中,我可以与summary属性进行交互。但是,当我尝试使用Django-y做任何事情时,例如 Post(title = foo,summary = bar),它会抛出错误。

So far so good, and in the console I can interact with the summary property just fine. But when I try to do anything Django-y with this, like Post(title="foo", summary="bar"), it throws a fit. Is there any way to get Django to play nice with Python properties?

推荐答案

不幸的是,Django模型不能很好地配合Python属性使用? Python属性。它的工作方式是,ORM仅识别QuerySet过滤器中的字段实例的名称。

Unfortunately, Django models don't play very nice with Python properties. The way it works, the ORM only recognizes the names of field instances in QuerySet filters.

您将无法引用 summary 在过滤器中,而是必须使用 _summary 。这很快就会变得凌乱,例如在多表查询中引用该字段,您必须使用类似

You won't be able to refer to summary in your filters, instead you'll have to use _summary. This gets messy real quick, for example to refer to this field in a multi-table query, you'd have to use something like

User.objects.filter(post___summary__contains="some string")

请参见 https://code.djangoproject.com/ticket/3148 有关财产支持的更多详细信息。

See https://code.djangoproject.com/ticket/3148 for more detail on property support.

这篇关于Django模型和Python属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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