Home > Software engineering >  How to merge two models into one model with django for admin?
How to merge two models into one model with django for admin?

Time:01-25

I have to identical models:

class AnimalGroup(models.Model):
    name = models.CharField(max_length=50, unique=True)    
    description = models.TextField(max_length=1000, blank=True)
    images = models.ImageField(upload_to="photos/groups")

class AnimalSubGroup(models.Model):
    name = models.CharField(max_length=50, unique=True)  
    description = models.TextField(max_length=1000, blank=True)
    images = models.ImageField(upload_to="photos/groups")
    

and they have a on-to-many relationship. So AnimalGroup can have multiple AnimalSubGroups

But as you see they have identical fields.

Question: how to make one model of this?

So that in Admin I can create animalgroups, like:

  • mammals
  • fish

And then I can create the subgroups. Like

  • bigCat and then I select mammals.

CodePudding user response:

Have them inherit an abstract base class and give the subgroup an additional foreign key:

class AbstractAnimalGroup(models.Model):
    name = models.CharField(max_length=50, unique=True)    
    description = models.TextField(max_length=1000, blank=True)
    images = models.ImageField(upload_to="photos/groups")
    
    class Meta:
        abstract = True

class AnimalGroup(AbstractAnimalGroup):
    pass

class AnimalSubGroup(AbstractAnimalGroup):
    parent = models.ForeignKey(AnimalGroup, on_delete=models.CASCADE)

If you want subgroups to be actual AnimalGroups, you can use multi-table inheritence:

class AnimalGroup(models.Model):
    name = models.CharField(max_length=50, unique=True)    
    description = models.TextField(max_length=1000, blank=True)
    images = models.ImageField(upload_to="photos/groups")

class AnimalSubGroup(AnimalGroup):
    parent = models.ForeignKey(AnimalGroup, on_delete=models.CASCADE)

Now, all AnimalSubGroups will be also contained in AnimalGroup.objects.all().

CodePudding user response:

You can use an abstract base model:

class NameDescImageModel(models.Model):
    name = models.CharField(max_length=50, unique=True)    
    description = models.TextField(max_length=1000, blank=True)
    images = models.ImageField(upload_to='photos/groups')

    class Meta:
        abstract = True


class AnimalGroup(NameDescImageModel):
    pass

class AnimalSubGroup(NameDescImageModel):
    group = models.ForeignKey(AnimalGroup, on_delete=models.CASCADE)
  • Related