Miknotauro
Miknotauro

Reputation: 31

Conditional related model on Django Many to Many Field

I'm wondering how to achieve this behavior, any help would be appreciate

class ModelA(models.Model):
    pass

class ModelB(models.Model):
    pass

class ModelC(models.Model):
    TYPE = (('A', 'ModelA'), ('B', 'ModelB'))
    type = models.CharField("model type", choices=TYPE, max_length=2, unique=True)
    field = models.ManyToManyField(ConditionalModel)

I want to do something like this in ModelC definition ->

if type="A":
    field = models.ManyToManyField(ModelA)
if type="B":
    field = models.ManyToManyField(ModelB)

Upvotes: 1

Views: 500

Answers (2)

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11665

create 2 m2m realations and do like below

class ModelA(models.Model):
    pass

class ModelB(models.Model):
    pass

class ModelC(models.Model):    
    TYPE = (('A', 'ModelA'), ('B', 'ModelB'))
    type = models.CharField("model type", choices=TYPE, max_length=2, unique=True)
    _m2m_A = models.ManyToManyField(ModelA)
    _m2m_B = models.ManyToManyField(ModelB)

    @property
    def field(self):
        if self.type == "A":
           return self._m2m_A
        elif self.type == "B":
           return self._m2m_B  

Upvotes: 1

Lemayzeur
Lemayzeur

Reputation: 8525

You can't have a conditional ManyToManyField to 2 different Models.
The best approach is to use GenericRelation which can receive any model.

Adding a foreign key from one of your own models to ContentType allows your model to effectively tie itself to another model class

class TaggedItem(models.Model):
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

content_object can receive any model instance.

Upvotes: 2

Related Questions