gpt4 book ai didi

Django 模型表单和对象数据库 ID

转载 作者:行者123 更新时间:2023-12-01 10:13:09 25 4
gpt4 key购买 nike

我有一个复杂的 django 对象,它具有其他类类型的属性。变成这样:

class Order:
contractor - type Person
some other fields....

在我的表单中,我希望能够从下拉列表中选择现有的 Person 对象,或者使用表单添加一个新对象。我已经设法创建表单和适当的工作流程,但问题在于保存订单本身,我根本无法获取已保存的 Person 实例的 id。我正在这样做:

def make_order(request):
if request.method == 'POST':
parameters = copy.copy(request.POST)
contractor_form = ContractorForm(parameters)
if contractor_form.is_valid():
contractor_form.save()
parameters['contractor'] = ???
form = OrderForm(parameters)
if form.is_valid():
form.save()
return HttpResponseRedirect('/orders/')
else:
form = OrderForm()
contractor_form = ContractorForm()

return render_to_response('orders/make_order.html', {'order_form' : form, 'contractor_form' : contractor_form})

因此,如果 POST 请求到达此方法,我首先检查是否已填写 ContractorForm - 我假设如果该表单有效,则它应该被使用。如果是,那么我保存它并希望将保存的对象的数据库 ID 分配给适当的字段,以便 OrderForm 找到它。

我所有的表单都是 ModelForms。

问题是:

  1. 有没有更好的方法来做到这一点? (从下拉列表中选择或添加到位)- 更好或更 Pythonic ;-)
  2. 使用 ModelForms 时如何获取保存的对象 ID?

已编辑

我的 ContractorForm 是:

class ContractorForm(ModelForm):
class Meta:
model = Contractor

没什么特别的。

最佳答案

save()应该返回新创建的实例。

if contractor_form.is_valid():
instance = contractor_form.save()
parameters['contractor'] = instance

其中 id 将是 instance.id,甚至更好 instance.pk .

pk vs. id :

Regardless of whether you define a primary key field yourself, or let Django supply one for you, each model will have a property called pk. It behaves like a normal attribute on the model, but is actually an alias for whichever attribute is the primary key field for the model. You can read and set this value, just as you would for any other attribute, and it will update the correct field in the model.

评论跟进:

默认情况下它确实有效,所以肯定有其他问题。

models.py

class Category(models.Model):
name = models.CharField(max_length=70)
slug = models.SlugField()

forms.py

from django import forms
from models import Category

class MyModelForm(forms.ModelForm):
class Meta:
model = Category

在 shell 中测试:

In [3]: from katalog.forms import MyModelForm
In [4]: data = {'name':'Test', 'slug':'test'}
In [5]: form = MyModelForm(data)
In [6]: instance = form.save()
In [7]: instance
Out[7]: <Category: Test>
In [8]: instance.id
Out[8]: 5L

关于Django 模型表单和对象数据库 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3654333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com