0

I am currently implementing a django app, for this I try to use a syntax that is consistent with Django's...

So here is what I am trying :

class Blablabla(Model):

    #this contains Blablabla's options
    class Meta:
        sort_key = lambda e: e

sort_key is a key function (for sorting purposes), but of course, it is understood as Meta's method (which is absolutely not what I want)!!!

Any workaround to this, that would still allow me to use this syntax ?

EDIT : Just an important precision ... the code I wrote is supposed to be written by somebody that uses the library ! That's why I don't want any dirty trick. And YES in Django it is really used just for options... of course Meta IS a class, but I say "it is not seen as a class", because it is not used as a class : you don't instantiate it, you don't put class methods, only class attributes... The Model has a metaclass that extracts everything from this Meta and handles all the options declared... But that's all ! It IS just a placeholder for options.

But OK that's True I never saw an option that is a function in Django... So I'll follow Ned an declare this sorting function as a method of Model that has to be overriden ...

4

4 回答 4

2

In general,

class Meta(object):
    sort_key= staticmethod(lambda e: e)

I've no idea if whatever magic Django does to transplant ‘meta’ members copes OK with decorated methods like this, but I don't see any inherent reason why not.

于 2010-09-16T23:36:41.127 回答
2

你为什么要sort_key投入MetaMeta用于 Django 选项,它不是放置您自己的方法的地方。模型可以在其上定义方法。我想你想要一些简单的东西:

class Blablabla(Model):

    def sort_key(self, e):
        return e
于 2010-09-17T02:08:47.893 回答
0

OP 在评论中写道“'Meta' 不应该被视为一个类”。如果是这样的话,也就是说,如果 Django 在Meta确实不是一个类(一个非常大的“如果”)时可以生存,那么就有可能满足 OP 避免使用最简单的解决方案的真正奇怪的愿望(只是stqticfunction围绕有lambda问题的解决方案) .

本质上,这需要编写一个(非常奇怪的)类来生成一个对象,其中属性查找绕过类对描述符对象的正常使用(每个函数都是一个描述符对象:也就是说,它有一个__get__Python 通常在查找时使用的方法类或其实例上的属性)。

这种荒谬的旋转的一般想法是......:

class MetaNotAClass(type):
   def __new__(mcl, clasname, bases, clasdict):
     if bases:
         usedict = {}
     else:
         usedict = clasdict
     usedict['__foo'] = clasdict
     return type.__new__(mcl, clasname, bases, usedict)
   def __getattr__(cls, atname):
      try: return getattr(cls, '__foo')[atname]
      except KeyError: raise AttributeError, atname

class NotAClass:
  __metaclass__ = MetaNotAClass


class Bah(NotAClass):
  def f(): return 'weird!'

print Bah.f()

当然,任何期望 Bah成为类的东西都会破坏(但是,你确实说它“不应该被视为一个类”,所以这基本上就是你所要求的:破坏任何认为它是的代码“被视为一个阶级”!-)。

于 2010-09-17T00:18:17.903 回答
0

你不能只创建一个简单的模块(meta?)并添加sort_key到它吗?然后继续前进,include无论您需要它...

于 2010-09-17T07:47:44.857 回答