Skip to main content
 首页 » 编程设计

python之Django 代理模型返回父模型

2025年05月04日27softidea

我在使用 django 1.6.5 时遇到了一个奇怪的问题。

在 distribution.models 我有:

from core.models import Book, Person 
 
class Proxy1(Book): 
    class Meta: 
        proxy = True 
 
class Proxy2(Person): 
    class Meta: 
        proxy = True 

这怎么会发生?:

>>> from distribution.models import Proxy1, Proxy2 
>>> type(Proxy1.objects.first()) 
<class 'core.models.Book'> 
>>> type(Proxy2.objects.first()) 
<class 'distribution.models.Proxy2'> 

知道在哪里寻找原因吗?

请您参考如下方法:

经过数小时的搜寻,我终于找到了罪魁祸首。 django-money 包中的 MoneyField 在模型管理器上做了一些黑魔法,以某种方式破坏了为代理模型返回正确的模型类。我提出了一个问题:https://github.com/jakewins/django-money/issues/80

我解决了一个简单的解决方法,通过手动覆盖代理类上的“对象”属性,如下所示:

class ProxyModel(SomeModelWithMoneyField): 
 
    # This fixes django-money that would else return parent objects 
    objects = models.Manager() 
 
    class Meta: 
        proxy=True