我不确定我是否会100%回答这个问题,因此我将按照以下假设运行:
每个Pizza
可以有多个Topping
s。每个Topping
可以有多个Pizza
s。但是,如果将aTopping
添加到Pizza
,Topping
则将自动具有Pizza
,反之亦然。
在这种情况下,最好的选择是关系表,Django很好地支持该关系表。它可能看起来像这样:
models.py
class PizzaTopping(models.Model):
topping = models.ForeignKey('Topping')
pizza = models.ForeignKey('Pizza')
class Pizza(models.Model):
name = models.CharField(max_length=50)
topped_by = models.ManyToManyField('Topping', through=PizzaTopping)
def __str__(self):
return self.name
def __unicode__(self):
return self.name
class Topping(models.Model):
name=models.CharField(max_length=50)
is_on = models.ManyToManyField('Pizza', through=PizzaTopping)
def __str__(self):
return self.name
def __unicode__(self):
return self.name
表格
class PizzaForm(forms.ModelForm):
class Meta:
model = Pizza
class ToppingForm(forms.ModelForm):
class Meta:
model = Topping
例:
>>> p1 = Pizza(name="Monday")
>>> p1.save()
>>> p2 = Pizza(name="Tuesday")
>>> p2.save()
>>> t1 = Topping(name="Pepperoni")
>>> t1.save()
>>> t2 = Topping(name="Bacon")
>>> t2.save()
>>> PizzaTopping(pizza=p1, topping=t1).save()
>>> PizzaTopping(pizza=p2, topping=t1).save()
>>> PizzaTopping(pizza=p2, topping=t2).save()
>>> tform = ToppingForm(instance=t2)
>>> tform.as_table()
u'<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" value="Bacon" maxlength="50" /></td></tr>\n<tr><th><label for="id_is_on">Is on:</label></th><td><select multiple="multiple" name="is_on" id="id_is_on">\n<option value="1">Monday</option>\n<option value="2" selected="selected">Tuesday</option>\n</select><br /> Hold down "Control", or "Command" on a Mac, to select more than one.</td></tr>'
>>> pform = PizzaForm(instance=p1)
>>> pform.as_table()
u'<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" value="Monday" maxlength="50" /></td></tr>\n<tr><th><label for="id_topped_by">Topped by:</label></th><td><select multiple="multiple" name="topped_by" id="id_topped_by">\n<option value="1" selected="selected">Pepperoni</option>\n<option value="2">Bacon</option>\n</select><br /> Hold down "Control", or "Command" on a Mac, to select more than one.</td></tr>'
>>> pform2 = PizzaForm(instance=p2)
>>> pform2.as_table()
u'<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" value="Tuesday" maxlength="50" /></td></tr>\n<tr><th><label for="id_topped_by">Topped by:</label></th><td><select multiple="multiple" name="topped_by" id="id_topped_by">\n<option value="1" selected="selected">Pepperoni</option>\n<option value="2" selected="selected">Bacon</option>\n</select><br /> Hold down "Control", or "Command" on a Mac, to select more than one.</td></tr>'
Pizza
可以看出:每个可以有多个Topping
s。每个Topping
可以有多个Pizza
s。但是,如果我添加一个Topping
到Pizza
,这是否Pizza
然后自动地有一个Topping
,反之亦然?