DetailView使用两个ForeignKey kwargs

时间:2014-06-01 23:46:26

标签: django python-2.7 django-class-based-views django-1.6

我试图通过使用通过url传递的两个关键字参数查询表来利用Django的基于类的通用DetailView。我试过覆盖get_queryset()和get_object()方法无济于事。我的模型看起来像这样(为了简洁而编辑,但如果缺少重要的东西,请告诉我):

# models

class Skill(models.Model):
    skill = models.CharField()

class User(AbstractBaseUser):
    username = models.CharField()

class UserSkills(models.Model):
    skill = models.ForeignKey(Skill)
    user = models.ForeignKey(User, to_field='username')
    value = models.CharField()

我对DetailView的网址如下所示:

url(
    regex=r"^(?P<username>[a-zA-Z0-9-]{1,25})/skills/(?P<skill>[a-zA-Z0-9 -._/]+)/$",
    view=views.UserSkillDetail.as_view(),
    name='userskill_detail',
),

观点:

class UserSkillDetail(DetailView):
    template_name = 'UserSkill_detail.html'
    context_object_name = 'skill'
    model = UserSkills

    def get_object(self, queryset=None):
        get_user = self.kwargs['username']
        get_skill = self.kwargs['skill']
        return get_object_or_404(UserSkills, user__username=get_user, skill__skill=get_skill)

我通过模板调试消息继续收到以下错误:

No UserSkills matches the given query.

虽然我能够通过shell成功查询以下内容:

>>> x = UserSkills.objects.get(user__username='user1', skill__skill='skill1')
>>> x
<UserSkills: user1@example.com: skill1>

已通过记录器和Django调试工具栏验证是否正确捕获了关键字参数(&#39; user1&#39;,&#39; skill1&#39;)。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

我的迁移序列存在问题(按预期顺序调用)。我重新配置了迁移,一切正常。