且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django:从表单中保存外键

更新时间:2023-12-01 22:11:10

我建议建立一个 code>方法,您知道如何将自己保存到数据库中。它遵循一般的模式,即表单通过form.save()执行其操作,所以应该直观地遵循。

I'd recommend building a save method on each of your forms which knows how to save itself to the database. It follows a general pattern that "the form performs its action via form.save()" so it should be intuitive to follow.

底线是现在你有一个毯子:对于所有形式的每个字段,将Thing属性设置为这些字段。

The bottom line is that right now you have a blanket: "for every field in all forms, set the Thing attribute to those fields".

由于实际上您具有每个表单的保存行为,我认为需要将实例传递给每个表单是有意义的,因此每个表单都有机会将数据保存在适用于其字段的方式。

Since in reality you have per-form save behavior, I think it makes sense to require passing the instance to each form so that each form has a chance to save data in the way appropriate for its fields.

class Form1(...):
   def save(self, thing):
      for field, value in self.cleaned_data.items():
          setattr(thing, field, value)

class Form2(...):
   def save(self, thing):
      thing.point = Point.objects.get_or_create(lat=self.cleaned_data.get('lat'), long=...)
      # note, you may not want get_or_create if you don't want to share points.

您的观点将变为:

for form in form_list:
    form.save(instance)

只是一个想法。

如果你想更加干涩,像其他表单的自动化一样,我会建立一个基础表单,它有一个已经定义的保存方法:

If you want to be more DRY about it and like the automation of your other forms, I'd build a base form which has a save method already defined:

class BaseSaveBehaviorForm(forms.Form):
     def save(self, thing):
         for field, value in self.cleaned_data.items():
             setattr(thing, field, value)

class NormalBehaviorForm(BaseSaveBehaviorForm):
     # your forms as usual


class SpecialSaveBehaviorForm(forms.Form):
     def save(self, instance):
         # do something unusual