我无法保存中间字段的数据。我有创建股票和投资组合的表格(此处未列出)。现在我正在尝试建立一个会员表格来链接两者。我遵循了 django 文档,并且代码在 API 中完美运行。然后在视图中,我可以将会员资格保存好(后来我在 API 中将其拉出来进行检查),但它并没有在 Stock 和 Portfolio 之间建立联系。在会员表格之后,我的数据库中保存了一个会员对象,但它没有将投资组合连接到股票。
提前致谢。
这是我的模型:
class Stock(models.Model):
name = models.CharField(max_length=160)
ticker = models.SlugField(max_length=20)
created = models.DateTimeField(auto_now_add=True, blank=True)
class Portfolio(models.Model):
name = models.CharField(max_length=160)
stocks = models.ManyToManyField(Stock, through='Membership')
class Membership(models.Model):
stock = models.ForeignKey(Stock)
portfolio = models.ForeignKey(Portfolio)
shares = models.IntegerField(default=0)
class StockForm(forms.ModelForm):
class Meta:
model = Stock
exclude = []
class PortfolioForm(forms.ModelForm):
class Meta:
model = Portfolio
exclude = []
class MembershipForm(forms.ModelForm):
class Meta:
model = Membership
exclude = []
这是我的views.py:
def membership_form(request):
if request.method == 'POST':
form = MembershipForm(request.POST, request.FILES)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.save()
membership = Membership.objects.create( portfolio=new_obj.portfolio ,stock=new_obj.stock)
membership.save()
return HttpResponseRedirect(reverse('portfolios', args=[]))
else:
form = MembershipForm(None)
return render(request, 'portfolio/form.html', {'form': form})