简体   繁体   中英

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'.

What am I doing wrong?

UPD: if you want to do like this, you need to use subclass Meta in your layer

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

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.

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 already adds a field id to your parent model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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