Django ManyToMany relationship with abstract base is impossible, but is there a better way?

Given the following models:

class BaseMachine(models.Model) fqdn = models.CharField(max_length=150) cpus = models.IntegerField() memory = models.IntegerField() class Meta: abstract = True class PhysicalMachine(BaseMachine) location = models.CharField(max_length=150) class VirtualMachine(BaseMachine) hypervisor = models.CharField(max_length=5) class Sysadmin(models.Model): name = models.CharField(max_length=100) admin_of = models.ManyToManyField... 

In this example, I would like to associate 1 sysadmin with many machines - be it an instance of either PhysicalMachine or VirtualMachine. I know that I cannot have ManyToMany with an abstract base, but I was wondering if there is a better way to achieve this than just having a separate ManyToMany field in sysadmin for each of the models? In this small example, which may be valid, but if you have more than two subclasses or there are other models that you need to associate with the base class, this becomes something more than can be controlled.

Thanks:)

+2
source share
2 answers

EDIT: I updated my soul, so one administrator can have many machines, and one machine can have many administrators:

 class Sysadmin(models.Model): name = models.CharField(max_length=100) class BaseMachine(models.Model): fqdn = models.CharField(max_length=150) cpus = models.IntegerField() memory = models.IntegerField() admins = models.ManyToManyField(Sysadmin) class Meta: abstract = True class PhysicalMachine(BaseMachine): location = models.CharField(max_length=150) class VirtualMachine(BaseMachine): hypervisor = models.CharField(max_length=5) In [1]: s1 = Sysadmin(name='mike') In [2]: s1.save() In [3]: m1 = PhysicalMachine(fqdn='test', cpus=1, memory=20, location='test') In [4]: m1.save() In [5]: m1.admins.add(s1) In [6]: m1.save() In [7]: m2 = VirtualMachine(fqdn='test', cpus=1, memory=20, hypervisor='test') In [8]: m2.save() In [9]: m2.admins.add(s1) In [10]: m2.save() In [11]: m1.admins.all() Out[11]: [<Sysadmin: Sysadmin object>] In [12]: m2.admins.all() Out[12]: [<Sysadmin: Sysadmin object>] 
+3
source

Do you find a general relationship using the contenttypes framework?

+2
source

Source: https://habr.com/ru/post/1392196/


All Articles