mightycode Newton
mightycode Newton

Reputation: 3949

How to merge two models into one model with django for admin?

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:

And then I can create the subgroups. Like

Upvotes: 0

Views: 80

Answers (2)

user2390182
user2390182

Reputation: 73470

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().

Upvotes: 3

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476813

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)

Upvotes: 1

Related Questions