我有两个Django模型:
class seller_event(models.Model):
event_id = models.AutoField(primary_key=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length = 300, default = 'Null')
description = models.CharField(max_length = 300, default = 'Null')
location = models.CharField(max_length= 300, default = 'Null')
cash_payment = models.BooleanField(default=True)
paytm_payment = models.BooleanField(default=False)
def __unicode__(self):
return str(self.event_id)
class seller_event_items(models.Model):
item_id = models.AutoField(primary_key=True)
event_id = models.ForeignKey(seller_event)
item_name = models.CharField(max_length = 300, default = 'Null')
item_price = models.CharField(max_length = 300, default = 'Null')
item_quant = models.CharField(max_length = 300, default = 'Null')
def __unicode__(self):
return str(self.item_id)
第二个表的外键是第一个表的主键。基本上,我试图将商品与销售相关联。我有这样的表格:
forms.py:
class Seller_event(forms.ModelForm):
class Meta:
model = seller_event
exclude = {'user'}
class Seller_event_items(forms.ModelForm):
class Meta:
model = seller_event_items
exclude = {'event_id'}
views.py:
def newlist(request):
if request.user.is_authenticated():
user = request.user
print user
if request.method == 'POST':
seller_event_form = Seller_event(request.POST)
seller_event_items_form = Seller_event_items(request.POST)
if seller_event_form.is_valid() and seller_event_items_form.is_valid():
new_seller_event = seller_event_form.save(commit=False)
new_seller_event.user = user
new_seller_event.save()
seller_event_items_form.save()
return redirect('/home')
else:
seller_event_form = Seller_event()
seller_event_items_form = Seller_event_items()
return render(request, 'home/newlist.html', {'seller_event_form': seller_event_form, 'seller_event_items_form': seller_event_items_form})
此处的表单有助于卖家创建销售,然后使用商品填充销售。
如何自动将items表上的fk设置为event_id(sell_events表的pk)?我已将其从表格中排除,但我不确定在此之后该怎么做。
提前致谢!
答案 0 :(得分:3)
在seller_event_items_form.save()
之前添加此行
你可以把它称为ForeignKey
seller_event_items.event_id = new_seller_event
答案 1 :(得分:1)
您的操作方式与您在new_seller_event上设置用户的方式完全相同。
事件与用户之间的关系与项目与事件之间的关系相同。