简体   繁体   English

Python-从继承模型的类继承

[英]Python - Inherit from class which inherit Model

Here is my problem: I try to create layer under 这是我的问题:我尝试在

models.Model 

My Model - 我的模特-

class MainModel(models.Model):
    @staticmethod
    def getIf(condition):
        results = __class__.objects.filter(condition)
        if results.count() > 0:
            return results.first()
        else:
            return None

And that's a model 那是一个模型

class User(MainModel):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=256)
    date_create = models.DateTimeField(auto_now_add=True)
    date_last_login = models.DateTimeField(null=True)

But my project is crushed with error - 但是我的项目被错误压垮了-

django.core.exceptions.FieldError: Local field 'id' in class 'User' clashes with field of the same name from base class 'MainModel'. django.core.exceptions.FieldError:类“用户”中的本地字段“ id”与基类“ MainModel”中同名的字段发生冲突。

What am I doing wrong? 我究竟做错了什么?

UPD: if you want to do like this, you need to use subclass Meta in your layer UPD:如果要这样做,则需要在图层中使用Meta类

class MainModel(models.Model):
    @staticmethod
    def getIf(condition:dict):
        results = __class__.objects.filter(condition)
        if results.count() > 0:
            return results.first()
        else:
            return None

    class Meta:
        abstract = True

Thanx, but I'm not trying to override fields, In my layer no one field is not defined. 谢谢,但是我没有尝试覆盖字段,在我的图层中没有一个字段没有定义。 I found my answer, I just have to read documentation. 我找到了答案,我只需要阅读文档。

if you want to do like this, you need to use subclass Meta in your layer 如果要这样做,则需要在图层中使用Meta类

class MainModel(models.Model):
    @staticmethod
    def getIf(condition:dict):
        results = __class__.objects.filter(condition)
        if results.count() > 0:
            return results.first()
        else:
            return None

    class Meta:
        abstract = True

Django adds a field id to all Models, you have to remove it. Django将字段id添加到所有模型,您必须将其删除。

Ok I understand your question better now, your answer is there: 好的,现在我对您的问题有了更好的了解,您的答案在那里:

In Django - Model Inheritance - Does it allow you to override a parent model's attribute? 在Django中-模型继承-是否允许您覆盖父模型的属性?

Django already adds a field id to your parent model. Django已经为您的父模型添加了一个字段ID。

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

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