1

我无法保存中间字段的数据。我有创建股票和投资组合的表格(此处未列出)。现在我正在尝试建立一个会员表格来链接两者。我遵循了 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})

我基于Django m2m 表单保存“通过”表的视图。

4

1 回答 1

1

编写一个自定义表单并将关系保存在其中。

我已将示例作为与我要发送的电子邮件相关联的电子邮件地址类别

class SendForm (forms.ModelForm) :

    To = forms.ModelMultipleChoiceField(
        queryset=EmailId.objects.filter(),required=False,widget=FilteredSelectMultiple(('To'), False))

    def __init__(self, *args, **kwargs):
        initial = kwargs.setdefault('initial', {})
        if 'instance' in kwargs:
            initial['To']=kwargs['instance'].To.all()
        super(SendForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        instance = forms.ModelForm.save(self, commit)
        instance.save(send=0)
        es = [e for es in self.cleaned_data['To']]

        for relation in instance.To.all():
            instance.To.remove(relation)
        for e in es:
            instance.To.add(e)

        instance.save(send=1)

        return instance
    class Meta:
        model =SentEmail
于 2013-07-28T14:27:59.310 回答