我有3个型号:
class POHeader(models.Model):
number = models.CharField(max_length="5", unique=True)
class Modules(models.Model):
# this has M:M relationship with the Service model
name = models.CharField(max_length="5", unique=True)
class Service(models.Model):
#id is the key field which is auto generated
# apart from other attributes ..
poheader = models.ForeignKey(POHeader)
modules = models.ManyToManyField(Module)
服务模型与POHeader内联。此外,模块还具有admin.py中使用的多个选择:
class ServiceForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ServiceForm, self).__init__(*args, **kwargs)
modules = forms.ModelMultipleChoiceField(
queryset=Module.objects.all(),
required=False,
widget=forms.CheckboxSelectMultiple())
class Meta:
"""
Service Model
"""
model = Service
现在的问题是,对于为每个服务选择的每个模块,我想为该模块添加其他详细信息。如何实现?这些属性是否需要添加到服务模型中?如何实现这一目标。例如,对于一个poheader 1条目:
service1 module1数量25 module2数量27
service2 module7 qty 2
在这里,我想为为服务选择的模块添加额外的属性数量qty
请记住,我们正在使用Service作为admin.TabularInline进行POHeader条目。
答案 0 :(得分:0)
如果我正确理解了这个问题,你需要为多对多关系创建一个模型。
class ServiceModule(models.Model):
service = models.ForeignKey(Service)
module = models.ForeignKey(Module)
quantity = models.PositiveIntegerField(default=0)
然后在多对多关系中指定它。
class Service(models.Model):
poheader = models.ForeignKey(POHeader)
modules = models.ManyToManyField(Module, through=ServiceModule)
https://docs.djangoproject.com/en/1.2/topics/db/models/#extra-fields-on-many-to-many-relationships
答案 1 :(得分:0)
注意这个
之间的区别modules = models.ManyToManyField(modules)
和这个
modules = models.ManyToManyField(Modules)
另外,根据1.2 docs,您应该添加到
modules = models.ManyToManyField(Module, through=ServiceModule)
this accepted question也可能有所帮助