2

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
3
  • Have you read the documentation on model inheritence? Commented Aug 28, 2017 at 12:49
  • Use user_id in place of id. Commented Aug 28, 2017 at 13:20
  • not, of course, if I asks )) ok, I found what I lost Commented Aug 28, 2017 at 13:26

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively, you could make MainModel a mixin, that inherits from just object, and then your actual model can be class User(MainModel, models.Model).
yee, thanks :) it was one of my trying, but I want to understand as much as I can and had to understand how can I do exactly it )
1

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.

1 Comment

But if I create it directly in class, which inherit models.Model all is fine - field id successfully created in db

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.