Django中使用什么方法属性? [英] What method attributes are used in Django?

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

问题描述

的文档中ModelAdmin.list_display 描述了在管理员的列表视图中配置方法/功能以使用和显示的几种方法:




  • admin_order_field (描述模型中用于按方法排序的字段)

  • allow_tags (允许HTML显示而不是转义)

  • short_description (设置标签对于列)

  • boolean (确定该字段是否应被视为一个布尔字段显示)



它将它们描述为方法属性。



附录



刚刚找到一些更多的方法/函数属性,用于模板过滤器




  • is_safe ,用于将模板过滤器标记为安全

  • needs_autoescape ,用于处理数据的自动转义



其他方法属性在Django(甚至是Python)中?还是这些真的是唯一的情况?



澄清



要清楚,这就是我



在以下代码中:

  class Foo (models.Model):
name = models.CharField(max_length = 100)
color = models.CharField(max_length = 100)
age = models.PositiveIntegerField()

def is_adult(self):
return age> 18
is_adult.boolean = True
is_adult.short_description =超过18?

def colored_name(self):
return'< span style =color:%s>%s< / span>'%(self.color,self.name)
colored_name.allow_tags = True
colored_name.short_desciption =Name
colored_name.admin_order_field =name

我所说的方法属性是 is_adult.boolean is_adult.short_description colored_name.allow_tags colored_name.short_description colored_name.admin_order_field

如果您需要更多详细信息,请阅读链接的文档。



附录#2



看起来这在 PEP 232:功能属性。 PEP指向列出功能属性的其他潜在用例的邮件列表帖子



  • 我需要将一个Java风格的类型声明与一个方法相关联,所以
    ,它可以基于Java类型的方法
    调度来识别。您将如何使用实例?


  • 我需要将语法规则与Python方法相关联,以便
    调用该方法解析器在输入数据中识别一个句法结构


  • 我需要将一个IDL声明与一个方法相关联,以便COM
    接口定义可以从源文件生成。


  • 我需要将XPath模式字符串与Python方法
    关联起来,当一个树步行者在XML DOM中发现
    特定模式时,可以调用该方法。


  • 我需要将多种形式的文档与方法相关联。
    它们针对不同的IDE,环境或语言进行了优化。



以下是允许方法属性可调用的实现



<$ p $来自django.contrib.admin导入的p> 来自datetime.datetime import的导入ModelAdmin


class ProfileAdmin(ModelAdmin):

list_display = ('votes_today')

class VotesToday:
def __call __(self,model_admin,obj):
today = now()。replace(hour = 0,minute = ,second = 0,microsecond = 0)
return obj.vote_set.filter(created__gte = today)

@property
def short_description(self):
return'今天投票(%s)'%now()。strftime('%B%d')

@property
def votes_today(self):
如果不是hasattr ,'__votes_today'):
self .__ votes_today = self.VotesT oday()
return self .__ vote_today


解决方案

有趣的是,你应该问这个问题,我在今天早些时候在django文档中使用不同的方法感到有点惊讶:

  def upper_case_name(obj):
return(%s%s%(obj.first_name,obj.last_name))。upper()
upper_case_name.short_description ='Name'
# !另外发生一个方法属性,一个属性
#分配给一个函数对象。

class PersonAdmin(admin.ModelAdmin):
list_display =(upper_case_name,)

所以,这意味着什么是功能定义是一种对象。一个更熟悉的方法可能是:

 >>> def myfunc():
...返回myvalue

#'myfunc'现在是本地范围中的function类型的对象。观察:

>>> type(myfunc)
< type:'function'>

#当然可以在'myfunc'上调用__call__:
>>> myfunc()
myvalue
>>> myfunc .__调用__()
myvalue

#并且因为'myfunc'也是一个普通对象,可以在其上定义属性。
myfunc.someattribute ='somevalue'
myfunc.is_a_function = True
myfunc.takes_args = False

所以,你的问题与python对象一直下降的想法有一点关系,也就是说,python中的一切都是一个对象。



现在为什么这很有用?假设您想要收集并使用一些您正在撰写的函数(或方法)中的元数据:

 来自运算符导入attrgetter 

def add(x,y):
return x + y

def subtract(x,y):
return x - y

def get_attribute_value(obj,attr):
return attrgetter(attr)(obj)

add.takes_args = True
add.number_of_args = 2
add.type_of_args = [int,int]
add.uses_black_magic = False

subtract.takes_args = True
subtract.number_of_args = 2
减法。 type_of_args = [int,int]
subtract.uses_black_magic = False

get_attribute_value.takes_args = True
get_attribute_value.number_of_args = 2
get_attribute_value.type_of_args = [object,str ]
get_attribute_value.uses_black_magic = True

然后,您可以使用这些方法属性有用的方式:

  def perform_function_checks(function_list): 
在功能列表中为afunc
如果getattr(afunc,'took_args'):
打印函数'%s'接受参数!如果getattr(afunc,'number_of_args'):
printfunction'%s'take%s args。%(afunc .__ name__,afunc。如果getattr(afunc,'type_of_args'):
printfunction'%s'take%s args:%s(afunc .__ name__,len(afunc.type_of_args),[,和.join(str(item))for afunc.type_of_args])
如果getattr(afunc,'uses_black_magic'):
打印哦不!函数'%s'使用黑魔法!%(afunc .__ name__,)

perform_function_checks([add,subtract,get_attribute_value])

#prints:
#function'add'接受args!如何不寻常!
#function'add'需要2个参数
#function'add'需要2个args:< type'int'>和< type 'int'>
#function'subtract'take args!多么不寻常!
#函数'subtract'需要2个参数
#function'subtract'需要2个args:< type' int'>和< type'int'>
#function'get_attribute_value'接受args!如何不寻常!
#function'get_attribute_value'需要2个参数
#function'get_attribute_value ''需要2个参数:< type'object'>和< type'str'>
#oh no!function'get_attribute_value'使用黑魔法!

当然,上面仅仅是为了说明的目的,如果你真的试图对函数a做这种类型的内省你可能想要使用'inspect'模块的对象,而不是添加你自己的bizarro元数据: http:// docs .python.org / library / inspect.html



有关此主题的更多信息,我建议此信息:



http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html



- 编辑:



抱歉,我没有解决您的允许方法的实现属性可以调用在附录#2下。



你的例子在这个讨论中有一点红色的鲱鱼。那里发生的是,有人正在使用@property装饰器来装饰一个方法,使其看起来像一个属性(a.k.a.属性)。考虑这个例子:

 #我们定义一个简单的类
class Foo():
#和a 正常属性
an_attribute ='a value'
#现在我们将使用@property装饰器来装饰一个方法
@property
def what_kind(self):
return str(self .__ class __.__ name__)

#现在,我们的Foo类的实例将具有属性'.what_kind'。

>>> bar = Foo()

#bar现在是一个foo的实例。

>>> bar.an_attribute
一个值

#,最后我们装饰的方法:

>>> bar.what_kind
Foo

请注意,我们不必调用'what_kind'以上返回值。我认为所有的@property装饰器都是自动调用 .__调用__()



所以,那个帖子正在做的是让它看起来django你只是添加一个普通的老属性到类,事实上,.short_description和.vote_today实际上是方法。



这里有更多关于@property装饰器/功能(内置的BTW,因此您不需要导入它)的信息:
http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/



- 编辑:修复了几个标记问题和一个打字错误。


Under the documentation for ModelAdmin.list_display it describes a few ways to configure a method/function for usage and display in an admin's list view:

  • admin_order_field (describes which field in the model to use for ordering by the method)
  • allow_tags (allows HTML to be displayed rather than escaped)
  • short_description (sets the label for the column)
  • boolean (determines if the field should be treated a boolean field for display)

It describes them as method attributes.

Addendum

Just found some more method/function attributes, used for template filters:

  • is_safe, used when marking a template filter as safe
  • needs_autoescape, used to deal with autoescaping of data

What other method attributes are there in Django (or even Python)? Or are these really the only cases?

Clarification

Just to be clear, this is what I'm talking about specifically.

In the following code:

class Foo(models.Model):
    name = models.CharField(max_length=100)
    color = models.CharField(max_length=100)
    age = models.PositiveIntegerField()

    def is_adult(self):
        return age > 18
    is_adult.boolean = True
    is_adult.short_description = "Over 18?"

    def colored_name(self):
        return '<span style="color: %s">%s</span>' % (self.color, self.name)
    colored_name.allow_tags = True
    colored_name.short_desciption = "Name"
    colored_name.admin_order_field = "name"

The method attributes I'm talking about are is_adult.boolean, is_adult.short_description, colored_name.allow_tags, colored_name.short_description and colored_name.admin_order_field.

If you need any more details, please read the linked documentation.

Addendum #2

Looks like this is partially covered in PEP 232: Function Attributes. The PEP points to a mailing list post that lists other potential use cases for function attributes:

  • I need to associate a Java-style type declaration with a method so that it can be recognized based on its type during Java method dispatch. How would you do that with instances?

  • I need to associate a "grammar rule" with a Python method so that the method is invoked when the parser recognizes a syntactic construct in the input data.

  • I need to associate an IDL declaration with a method so that a COM interface definition can be generated from the source file.

  • I need to associate an XPath "pattern string" with a Python method so that the method can be invoked when a tree walker discovers a particular pattern in an XML DOM.

  • I need to associate multiple forms of documentation with a method. They are optimized for different IDEs, environments or languages.

Here's an implementation that allows method attributes to be callable:

from django.contrib.admin import ModelAdmin
from datetime.datetime import now

class ProfileAdmin(ModelAdmin):

    list_display = ('votes_today',)

    class VotesToday:
        def __call__(self, model_admin, obj):
            today = now().replace(hour=0, minute=0, second=0, microsecond=0)
            return obj.vote_set.filter(created__gte=today)

        @property
        def short_description(self):
            return 'Votes today (%s)' % now().strftime('%B %d')

    @property
    def votes_today(self):
        if not hasattr(self, '__votes_today'):
            self.__votes_today = self.VotesToday()
        return self.__votes_today

解决方案

funny that you should ask about this, I was just a bit surprised by a different use of this in the django documentation earlier today:

def upper_case_name(obj):
    return ("%s %s" % (obj.first_name, obj.last_name)).upper()
upper_case_name.short_description = 'Name'
# !!! another occurrence of a "method attribute," an attribute
# assigned to a function object.

class PersonAdmin(admin.ModelAdmin):
    list_display = (upper_case_name,)

So, what this means, essentially, is that function definitions are a type of object. A more familiar way of saying this might be:

>>> def myfunc():
...   return "myvalue"

# 'myfunc' is now an object of type 'function' in the local scope. observe:

>>> type(myfunc)
<type: 'function'>

# you can, of course call __call__ on 'myfunc':
>>> myfunc()
"myvalue"
>>> myfunc.__call__()
"myvalue"

# and because 'myfunc' is also a normal object, you can define attributes on it.
myfunc.someattribute = 'somevalue'
myfunc.is_a_function = True
myfunc.takes_args = False

So, your question has a bit to do with the idea that python is "objects all the way down," that is, that everything in python is an object.

Now why is this useful? Suppose you want to collect and use some metadata on a set of functions (or methods) that you're writing:

from operator import attrgetter

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def get_attribute_value(obj, attr):
    return attrgetter(attr)(obj)

add.takes_args = True
add.number_of_args = 2
add.type_of_args = [int, int]
add.uses_black_magic = False

subtract.takes_args = True
subtract.number_of_args = 2
subtract.type_of_args = [int, int]
subtract.uses_black_magic = False

get_attribute_value.takes_args = True
get_attribute_value.number_of_args = 2
get_attribute_value.type_of_args = [object, str]
get_attribute_value.uses_black_magic = True

You could then use these 'method attributes' in a useful way:

def perform_function_checks(function_list):
    for afunc in function_list:
        if getattr(afunc, 'takes_args'):
            print "function '%s' takes args! how unusual!" % (afunc.__name__,)
        if getattr(afunc, 'number_of_args'):
            print "function '%s' takes %s args." % (afunc.__name__, afunc.number_of_args)
        if getattr(afunc, 'type_of_args'):
            print "function '%s' takes %s args: %s" (afunc.__name__, len(afunc.type_of_args), [", and ".join(str(item)) for item in afunc.type_of_args])
        if getattr(afunc, 'uses_black_magic'):
            print "oh no! function '%s' uses black magic!" % (afunc.__name__,)

perform_function_checks([add, subtract, get_attribute_value])

# prints:
# function 'add' takes args! how unusual!
# function 'add' takes 2 args.
# function 'add' takes 2 args: <type 'int'>, and <type 'int'>
# function 'subtract' takes args! how unusual!
# function 'subtract' takes 2 args.
# function 'subtract' takes 2 args: <type 'int'>, and <type 'int'>
# function 'get_attribute_value' takes args! how unusual!
# function 'get_attribute_value' takes 2 args.
# function 'get_attribute_value' takes 2 args: <type 'object'>, and <type 'str'>
# oh no! function 'get_attribute_value' uses black magic!

Now, of course, the above is for illustrative purposes only, if you were actually trying to do this type of introspection on functions and objects you'd probably want to use the 'inspect' module, rather than adding your own bizarro metadata: http://docs.python.org/library/inspect.html

For more information on this topic, I'd recommend this post:

http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html

-- EDIT:

sorry, I didn't address your "implementation that allows method attributes to be callable" under addendum #2.

Your example there is a bit of a red herring in this discussion. What's going on there, is that someone is using the @property decorator to decorate a method to make it look like a property (a.k.a. 'attribute'). Consider this example:

# let's define a simple class
class Foo():
    # and a "normal" attribute
    an_attribute = 'a value'
    # now a method that we'll decorate with the @property decorator
    @property
    def what_kind(self):
        return str(self.__class__.__name__)

# now, instances of our Foo class will have the attribute '.what_kind'.

>>> bar = Foo()

# bar is now an instance of foo.

>>> bar.an_attribute
"a value"

# and finally our decorated method:

>>> bar.what_kind
"Foo"

Note that we did not have to call 'what_kind' above to return the value. I think that all the @property decorator does is automatically call .__call__()

so, what the author of that post is doing is making it look to django that you're just adding a "plain old" attribute to the class, when, in fact, .short_description and .votes_today are actually methods.

Here's more information on the @property decorator/function (which is builtin, BTW, so you don't need to import it): http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/

-- EDIT: fixed a couple of markup problems, and a typo.

这篇关于Django中使用什么方法属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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