views.py
class BHA_UpdateView(UpdateView):
template_name = 'bha_test.html'
context_object_name = 'bha'
model = BHA_overall
success_url = reverse_lazy('well_list')
pk_url_kwarg = 'pk_alt'
form_class = BHA_overall_Form
def get_object(self, queryset=None):
pk = self.kwargs.get(self.pk_url_kwarg)
api = get_well_api(self.request)
current_bha = BHA_List.objects.filter(well=api, id=pk)[0]
return current_bha
forms.py
class BHA_overall_Form(forms.ModelForm):
class Meta():
model = BHA_overall
fields = '__all__'
models.py
class BHA_List(models.Model):
well = models.ForeignKey(WellInfo, 'CASCADE', related_name='bha_list')
bha_number = models.CharField(max_length=100)
class BHA_overall(models.Model):
bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_overall')
drill_str_name = models.CharField(max_length=111)
depth_in = models.CharField(max_length=111)
BHA_List
包含BHA对象的列表。每个BHA对象都有许多子对象,BHA_overall
是其中之一。
我的网址看起来像这样:
re_path(r'^bha/(?P<pk_alt>[-\w]+)$', base_views.BHA_UpdateView.as_view(), name='bha')
理想情况下,pk_url_kwarg = 'pk_alt'
应该在BHA_List
中查找对象,并导航到一个页面,您可以在其中更新有关BHA_List
中该特定对象的信息。我必须重写get_object()
,以便即使模型是pk_alt
,BHA_List
也会查找BHA_overall
。但是问题是,表单不会保存到数据库,因为get_object()
返回BHA_List
对象,而model = BHA_overall
所以看起来像这样:
You can now edit [ BHA 2 ]: # url = .../bha/2
BHA Overall Information -
Drill_str_name: []
Depth_in: []
...
Other Child Model -
other_field: []
other_field: []
我需要pk_url_kwarg = 'pk_alt'
来查询BHA_List
实例以生成唯一的url
,并且我需要BHA_overall_Form
显示用户可以编辑的输入字段,并将该用户输入保存到D B。但是我当前的代码集不起作用。
我对UpdateView的选择是错误的,因为它并不是要获取一个对象并更新另一个对象。谁能给我关于使用哪种CBV的建议,并提供一些适用于我的案例的示例代码?