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
Tsagana Nokhaeva
  • 630
  • 1
  • 6
  • 25
Maksim Zarechnyi
  • 407
  • 3
  • 16

2 Answers2

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
Maksim Zarechnyi
  • 407
  • 3
  • 16
  • Alternatively, you could make MainModel a mixin, that inherits from just `object`, and then your actual model can be `class User(MainModel, models.Model)`. – Daniel Roseman Aug 29 '17 at 10:09
  • 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 ) – Maksim Zarechnyi Aug 29 '17 at 10:24
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.

user2021091
  • 561
  • 2
  • 11