2011-09-18 15 views
1

我正在研究將代碼庫從使用app engine patch轉換爲使用django-nonrel時遇到的挑戰。如何用Django函數替換應用程序引擎modelclass.properties()?

多次在這個代碼庫中發生的事情之一是迭代實體的所有屬性。例如,比較器,拷貝構造函數,__str__等價物等等。

簡化的例子:

def compare_things(thing_a, thing_b): 
    '''Compare two things on properties not in Thing.COMPARE_IGNORE_PROPS''' 
    if type(thing_a) != type(thing_b): return "Internal error" 

    for prop in Thing.properties(): 
    if prop not in Thing.COMPARE_IGNORE_PROPS: 
     attr_a = getattr(thing_a, prop) 
     attr_b = getattr(thing_b, prop) 
     if attr_a != attr_b: 
     return prop + ": " + str(attr_a) + " is not equal to " + str(attr_b) 
    return '' 

然而,屬性()函數是從google.appengine.ext.db.Model。

如果我想使用django-nonrel,我的所有模型對象將來自django.db.models.Model。

該類中是否有相同的功能?

回答

0

我去睡覺,醒來時有一個近似的答案。可以使用dir來遍歷類成員。類似於(未經測試):

from django.db import models 

def properties(model_class): 
    ret = [] 
    for name in dir(model_class): 
    thing = getattr(model_class, name) 
    if (isinstance(thing, models.Field)): 
     ret.append(name) 
    return ret 
相關問題