开发者

django one form multiple tables

A form collects first name, email, password and grade.

Can I save this information in two tables using something like this?

 def save(self):
    new_user = User.objects.create_user(first=self.cleaned_data['first'], email=self.cleaned_data['email'], password=self.cleaned_data['password'])
    new_grade = Grade.objects.create_grade(grade=self.cleaned_data['grade'])
    return开发者_运维问答 new_user, new_grade

Is this possible? What would be a better way of doing this?


It's absolutely possible and normal to do such a thing. A form doesn't have to resemble a model just because ModelForms do. Forms are simply a way of describing the input that is required for a particular use case. What you do with that data is entirely up to you. That includes saving it across a number of different models.

Note that it's not a requirement to return the new instances that you've created in a regular form. It is just convention. If you need access to the new instances after the save, then by all means, return them.


it's better to coding like:

if new_user:
    ## create other tables..
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜