gpt4 book ai didi

python - 关于Django的OneToOneField、ManyToManyField和ManyToOneField的解释

转载 作者:行者123 更新时间:2023-12-01 06:03:41 25 4
gpt4 key购买 nike

我对 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 检索到模型表单中时,我收到此错误:“ModelFormOptions”对象没有属性“many_to_many”。我怀疑这行supplier = models.ForeignKey(Supplier)有问题。有人可以解释一下何时使用 ForeignKey 或关系字段 (OneToOneFields, ManyToManyFields, ManyToOneFields)

编辑:模型表单:

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'

最佳答案

您正在使用 ItemForm 实例实例化 ItemInfoForm。而 instance 应该是 ItemInfo 实例,而不是表单

正确的行:

item_info_form = ItemInfoForm(instance=item_info)

关于python - 关于Django的OneToOneField、ManyToManyField和ManyToOneField的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9076257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com