如何将更新视图与ForeignKey

如何将更新视图与ForeignKey

本文介绍了如何将更新视图与ForeignKey / OneToOneField一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class ModTool(models.Model):
...
issue = models.OneToOneField(Issue)
priority = models.CharField(max_length=1, choices=PRIORITY, blank=True)
status = models.CharField(max_length=1, choices=STATUS, default='O', blank=True)

url

url(r'^moderate/(?P<pk>\d+)', ModEdit.as_view(),name='moderation')

视图

class Modedit(UpdateView):

    model = ModTool
    template_name = 'myapp/moderate.html'
    fields = ['priority','status']

这时,我无法弄清楚如何设置此视图来编辑特定的ModTool实例,该实例具有pk中给出的Issue的onetoonefield。

At this point I am not able to figure out how to set this view to edit the particular ModTool instance which has the onetoonefield with Issue given in the pk.

推荐答案

您可以为此使用 slug_field slug_url_kwarg 属性:

You can use the slug_field and slug_url_kwarg attributes for this:

url(r'^moderate/(?P<issue_id>\d+)', ModEdit.as_view(),name='moderation')

class Modedit(UpdateView):
    slug_field = 'issue_id'
    slug_url_kwarg = 'issue_id'
    model = ModTool
    template_name = 'myapp/moderate.html'
    fields = ['priority','status']

这将对 issue_id =< issue_id> 进行查找,其中 issue_id 是URL中捕获的问题的主键。

This will do a lookup on issue_id=<issue_id> where issue_id is the issue's primary key as captured in the url.

我将关键字参数 pk 重命名为 issue_id 以防止名称与主键的查找冲突。否则,将发生一个附加过滤器,该过滤器使用问题的值在 ModTool 的主键上进行过滤。首要的关键。

I've renamed the keyword argument pk to issue_id to prevent a name clash with the lookup for the primary key. Otherwise an additional filter would take place that filtered on the ModTool's primary key with the value for the Issue's primary key.

这篇关于如何将更新视图与ForeignKey / OneToOneField一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 06:56