Django中的OneToOneField、ManyToManyField和ManyToOneField解释
我对Django的对象模型有点困惑。我有这样的模型:
# Create your models here.
class Item(models.Model):
code = models.CharField(max_length=200, unique=True)
barcode = models.CharField(max_length=300)
desc = models.CharField('Description',max_length=500)
reg_date = models.DateField('registered date')
registrar = models.CharField(max_length=100)
def __unicode__(self):
return self.code + ' : ' + self.desc
class ItemInfo(models.Model):
item = models.OneToOneField(Item, primary_key=True)
supplier = models.ForeignKey(Supplier)
stock_on_hand = models.IntegerField()
stock_on_order = models.IntegerField()
cost = models.IntegerField()
price = models.IntegerField()
unit = models.CharField(max_length=100)
lead_time = models.IntegerField()
但是当我尝试把Item和ItemInfo放到modelforms里时,出现了这个错误:'ModelFormOptions' object has no attribute 'many_to_many'
。我怀疑这行代码有问题:supplier = models.ForeignKey(Supplier)
。有人能告诉我什么时候应该使用ForeignKey
,还有其他的关系字段,比如(OneToOneFields, ManyToManyFields, ManyToOneFields)
吗?
编辑:ModelForm:
class ItemForm(ModelForm):
class Meta:
model = Item
widgets = {
'registrar' : TextInput(attrs={'ReadOnly' : 'True'})
}
class ItemInfoForm(ModelForm):
class Meta:
model = ItemInfo
exclude = ('item')
这是我如何生成带有模型中填充值的表单:
def details(request, code):
csrf_context = RequestContext(request)
current_user = User
if request.user.is_authenticated():
item = Item.objects.get(pk=code)
item_info = ItemInfo.objects.get(pk=item.pk)
item_form = ItemForm(instance=item)
item_info_form = ItemInfoForm(instance=item_form)
return render_to_response('item/details.html',
{'item_form' : item_form, 'item_info_form' : item_info_form},
csrf_context)
else:
return render_to_response('error/requires_login.html', csrf_context)
Traceback:
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "G:\tulip\stock\item\views.py" in details
131. item_info_form = ItemInfoForm(instance=item_form)
File "C:\Python27\lib\site-packages\django\forms\models.py" in __init__
237. object_data = model_to_dict(instance, opts.fields, opts.exclude)
File "C:\Python27\lib\site-packages\django\forms\models.py" in model_to_dict
112. for f in opts.fields + opts.many_to_many:
Exception Type: AttributeError at /item/details/1/
Exception Value: 'ModelFormOptions' object has no attribute 'many_to_many'
1 个回答
2
你正在用 ItemForm
的实例来创建 ItemInfoForm
。其实,instance
应该是 ItemInfo
的实例,而不是表单。
正确的代码应该是:
item_info_form = ItemInfoForm(instance=item_info)