I think this may be more SQL than Django but Django is what I’m working in. What I am trying to do is to come up with a object model which can have many properties but is constrained to only 1 property type per object.
Say we have 3 property types:
- is_cool
- is_happy
- is_mean
Suppose I have an object (MyObject) which can have * (0-All) of these properties applied to it but only one of each.
So I think this is diagramed as follows (please correct me if I’m wrong):

In Django I am stuggling with this constraint. I want it at the db level i.e using unique_together.
Here is what I have..
PROP_VALUE_CHOICES = (("URL", "url"),
("Boolean", "bool"),
("String", "char"),
("Person", "person"))
class PropertyType(models.Model):
name = models.CharField(max_length=32)
value_type = models.CharField(max_length=32, choices=PROP_VALUE_CHOICES)
class Property(models.Model):
type = models.ForeignKey(PropertyType)
value = models.CharField(max_length=32)
class MyObjectA(models.Model):
properties = models.ManyToManyField(Property, related_name="MyObjectA")
class MyObjectB(models.Model):
properties = models.ManyToManyField(Property, related_name="MyObjectB")
So the questions:
- Is the above picture the correct way to document what I’m trying to accomplish.
- My model is not complete – what am I missing and where do I apply the
unique togetherconstraint on the Object name and property type.
BTW – This is similar to this post but they used a through which I’m not sure I need??
Thanks!!
In case anyone really is looking for this answer…
Using Abstract Base Class I created the following structure which should work. Granted it no longer represents the picture completely but does solve the problem.
Posted in case I need this again in the future!