属性是否适用于 Django 模型字段? [英] Do properties work on Django model fields?

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

问题描述

我认为问这个问题的最好方法是使用一些代码...我可以这样做:

I think the best way to ask this question is with some code... can I do this:

class MyModel(models.Model):    
    foo = models.CharField(max_length = 20)    
    bar = models.CharField(max_length = 20)  

    def get_foo(self):  
        if self.bar:  
            return self.bar  
        else:  
            return self.foo  

    def set_foo(self, input):  
        self.foo = input  

    foo = property(get_foo, set_foo)  

或者我必须这样做:

class MyModel(models.Model):
    _foo = models.CharField(max_length = 20, db_column='foo')
    bar = models.CharField(max_length = 20)

    def get_foo(self):
        if self.bar:
            return self.bar
        else:
            return self._foo

    def set_foo(self, input):
        self._foo = input

    foo = property(get_foo, set_foo)

注意:您可以通过将 db_column 传递给模型字段,将数据库中的列名保留为foo".当您在现有系统上工作并且不想无缘无故地进行数据库迁移时,这非常有用

note: you can keep the column name as 'foo' in the database by passing a db_column to the model field. This is very helpful when you are working on an existing system and you don't want to have to do db migrations for no reason

推荐答案

模型字段已经是属性,所以我会说你必须用第二种方法来避免名称冲突.

A model field is already property, so I would say you have to do it the second way to avoid a name clash.

当您定义 foo = property(..) 时,它实际上覆盖了 foo = models.. 行,因此该字段将不再可访问.

When you define foo = property(..) it actually overrides the foo = models.. line, so that field will no longer be accessible.

您需要为属性和字段使用不同的名称.事实上,如果您按照示例 #1 中的方式进行操作,当您尝试访问该属性时,您将遇到无限循环,因为它现在尝试返回自身.

You will need to use a different name for the property and the field. In fact, if you do it the way you have it in example #1 you will get an infinite loop when you try and access the property as it now tries to return itself.

也许您还应该考虑不使用 _foo 作为字段名称,而是使用 foo,然后为您的属性定义另一个名称,因为属性不能用于QuerySet,所以当你做一个过滤器时你需要使用实际的字段名称.

Perhaps you should also consider not using _foo as a field name, but rather foo, and then define another name for your property because properties cannot be used in QuerySet, so you'll need to use the actual field names when you do a filter for example.

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

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