Message info From:trubliphone Subject:constraining one model\'s attributes with another\'s Date:Thu, 12 Apr 2012 09:34:03 -0600


I am at my wit's end trying to come up with a structure to do the
following. I have a "MasterModel" that acts as a template for an
"InstanceModel." The MasterModel defines a set of name/value pairs.
Each InstanceModel must have a name that corresponds to one of the
names of the MasterModel and a value chosen from the set of values of
that same MasterModel. So far I have the following code:

class MasterModel(models.Model):
name = models.CharField()
values = MasterValueField()

(MasterValueField is a custom field class that overloads "to_python"
and "value_to_string" such that it stores a string in the database but
returns a list of tuples in Python - of the sort that can be passed to
the "choices" attribute of a field.)

class InstanceModel(models.Model):
name = models.CharField()
values = models.CharField()

def __init__(self,*args,**kwargs):
# not sure if this is a good way to do things
master = kwargs.pop("master",None)
if master:
self._meta.get_field_by_name("name")[0].default =
self._meta.get_field_by_name("value")[0]._choices = master.values

Now I have a class with a relationship to InstanceModel:

class MyClass(models.Model):
myField = models.CharField()
myOtherField = models.CharField()
instances = models.ManyToManyField("InstanceModel")

There is a form based on MyClass, and a formset based on
InstanceModel. These both get rendered properly in the view. What I
am struggling with is figuring out how to initialize the instances.

When I add a new InstanceModel form in the formset, how can I ensure
that its name/value fields are constrained by the name/value fields of
an appropriate MasterModel?

I hope this is clear.

Many thanks for your help.

You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to
To unsubscribe from this group, send email to
For more options, visit this group at