简体   繁体   English

使用Django访问覆盖对象中的嵌套属性

[英]Accessing nested attributes in overwritten object using Django

posting this here ; 在这里发表; I believe I'll have some trouble figuring it out and it may just save me some time. 我相信我在解决它时会遇到一些麻烦,这可能会节省一些时间。

In python you can do this : 在python中,您可以执行以下操作:

>>> class Toto():
...     def w(self):
...         print(self.name)
...
...
...
>>> class Tata(Toto):
...     name = 'Hehehehe'
...
...
>>>
>>> e = Tata()
>>> e.w()
Hehehehe
>>>

Tough, using Django i'm stuck up with this error in the exact same context : 艰难,使用Django我在完全相同的上下文中陷入了这个错误:

object has no attribute 'name'

So I tried figuring out if some of my objects didn't had an attribute 'name' but it seems they all have it. 因此,我尝试确定我的某些对象是否没有属性“名称”,但似乎它们都具有属性。

Two questions : 两个问题:

Any limitation from Django side for this kind of thing ? 从Django方面对这种事情有什么限制吗?

How can I check which object throws the error so I can check it properly has the attribute ? 如何检查哪个对象引发了错误,以便可以正确地检查它是否具有属性?

I've been able to figure it out ! 我已经知道了!

So Model overwriting creates a new attribute in the host Class 因此,模型覆盖会在宿主类中创建一个新属性

class Base(models.Model):
    def __str__(self):
        objs = ['Extended'] # name of the overwriting object
        for ob in objs:
            try:
                return getattr(self, ob).name
            except:
                pass
        return 'Unbinded overwritten object'

class Extended(models.Model):
    name = models.CharField(max_length=300)

Base gets a new attribute called extended. Base获得了一个称为扩展的新属性。 So accessing custom attributes inside required passing through the overwriting object name. 因此,访问内部的自定义属性需要通过覆盖对象名称进行传递。

> t = Extended(name='test')
> t.save()
> bases = Base.objects.all()
> b[0].Extended.name
'test'

Happy Christmas everybody 大家圣诞节快乐

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM