Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django duplicate model definition/fields

Here's what I was using:

class a(models.Model):
    x = models.CharField()

class b(a):
    pass

The problem with this is that when an instance of b is created, an instance of a is also created, I'm guessing this is because b is inheriting some property that Django assigns such as the database table. I would like to have b have all the fields and methods so that this duplication does not happen. How can this be done without simply copy and pasting all the code from a to b or using an abstract base class c and have a and b both inherit from c (I'd like to only have two models/classes)? Would you have to use metaclasses?

like image 335
weeb Avatar asked Mar 07 '26 15:03

weeb


1 Answers

class A(models.Model):
    #some fields here
    x = models.CharField()
    class Meta:
        abstract = True

class B(A):
    pass

A will be an abstract class, and you cannot use this class alone. But as I understood, you want to have two real classes A and B. In this case you need a third (abstract) class C. So they will inherit the fields from the abstract one and add extra fields to them.

For example: suppose that abstract is C

class C(models.Model):
    # the common fields 
    class Meta:
        abstract = True
class A(C):
    #extra fields if you need or pass
class B(C):
     #extra fields if you need or pass
like image 183
aysekucuk Avatar answered Mar 09 '26 05:03

aysekucuk