Reputation: 31
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
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
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