Django的ModelForm外键下拉列表通过__str__但存储了fkey_id

时间:2018-08-21 10:49:23

标签: python django django-models django-forms django-generic-views

有两个模型,我想将一个模型的列字段存储到另一个模型。

models.py:

class Company(models.Model):
   name = ...
 def __str__(self):
         return self.name

class Rate(models.Model):
   company = models.ForeignKey(Company)
   currency = ...
   name = ...

 def __str__(self):
         return self.name + " " + self.currency

class Client(models.Model):
   name = ...
   currency = ....
   company = models.ForeignKey(Company)
   base_rate = models.ForeignKey(Rate)

 def __str__(self):
         return self.name

forms.py:

class ClientForm(forms.ModelForm):
    class Meta:
        model = Client
        fields = (
               "name",                
               "company",
               "base_rate", )

views.py:

class ClientCreateView(FormView):
    template_name = "client/new_package.html"
    form_class = ClientForm
    success_url = reverse_lazy("home")

    def form_valid(self, form):
        detail = form.save(commit=False)
        base_rate_id = form.cleaned_data['base_rate']
        detail.currency = Rate.objects.values_list("currency", flat=True).filter(base_rate_id=base_rate_id)
        detail.save()

        if detail is not None:
            return redirect('display_package' , detail.id)
        else:
            return super(ClientCreateView, self).form_valid(form)

基本上,我希望从Rate模型中将所选货币值保存到我的客户端模型中。任何帮助将不胜感激,因为从清除的数据中我得到的是 str 返回值,而不是选定的选项id值(即来自客户端模型的 str )。

1 个答案:

答案 0 :(得分:1)

我不确定您为什么要这么做。但更重要的是,为什么要使用filtervalues_list?您需要获取值并将其存储。

detail = form.save(commit=False)
detail.currency = form.cleaned_data['base_rate'].currency
detail.save()