python - Django 。如何在子模型中存储来自 mixin 的父模型字段?

标签 python django django-models django-rest-framework

请问我的 Django 项目中的模型关系有问题。例如,我有一个模型 Foo 继承自模型混合 FooBarMixin ,它是一个抽象类和 Bar 这是一个模型但有一个 OnetoOneFoo 的关系。基本上这是当前的实现。

class Foo(FooBarMixin):
        pass

class FooBarMixin(model.Model):
    bar = model.OneToOneField(Bar, on_delete=CASCADE,             
                     related_name="tracked_%(class)s")
    class Meta:
         abstract = True

class Bar(model.Model):
     pass

是否可以在不使用 OnetoOne 关系的情况下将 Bar 数据存储在子模型 Foo 上?如果是这样,我该怎么做?谢谢

最佳答案

Sorry I meant I want the fields in Bar to be visible on the Foo table.

根据您的评论,您因此想要在 Foo 实例中获取 Bar 关系的字段。

我们可以通过修补 __getattr__ 函数来做到这一点:

class Foo(FooBarMixin):

    def __getattr__(self, name):
        <b>try:</b>
            return super(Foo, self).__getattr__(name)
        <b>except AttributeError:</b>
            <b>return getattr(self.bar, name)</b>

因此,如果属性不能Foo 实例本身获取,我们将回退到相应的 self.bar 对象上,并且旨在获取该位置的属性。

设置属性需要以类似的方式覆盖 __setattr__ 函数,尽管我不建议这样做,因为它会引入各种副作用(保存相应的 . bar 对象等)。

关于python - Django 。如何在子模型中存储来自 mixin 的父模型字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51260225/

相关文章:

python - 在 slurm 上使用 python 的多处理

python - 如何正确运行 setup.py 文件?

python - 为什么在 Python 3.8 中是 sqrt(x*x + y*y) != math.hypot(x, y)?

python - 如何检查 Django Queryset 是否返回多个对象?

Django Admin,访问反向多对多

python - 如何在 python 中一次读取多个 csv 文件?

python - Django 全局变量

python - 如何向类 View 添加逻辑

django - 如果模型中已存在相同的数据,如何停止 Post 请求

python - 如何使用 Django ORM 在没有数百个查询的情况下选择多对一?