Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django 1.5中的多字段查找模型_Python_Django_Url_Slug_Permalinks - Fatal编程技术网

Python Django 1.5中的多字段查找模型

Python Django 1.5中的多字段查找模型,python,django,url,slug,permalinks,Python,Django,Url,Slug,Permalinks,我有一个模型 class ModelName(models.Model): type = models.ForeignKey(AnotherModel) slug = models.SlugField(editable=False) class Meta: unique_together = (('type', 'slug'),) @models.permalink def get_absolute_url(self):

我有一个模型

class ModelName(models.Model):
    type = models.ForeignKey(AnotherModel)
    slug = models.SlugField(editable=False)

    class Meta:
        unique_together = (('type', 'slug'),)

    @models.permalink
    def get_absolute_url(self):
        return ('model_detail', (), {'type': self.type.slug, 'slug': self.slug})
和URL

urlpatterns = patterns('',
    url(r'^(?P<type>[-\w]+)/(?P<slug>[-\w]+)/$', ModelDetailView.as_view(), name='detail'),
)

但是我得到了异常MultipleObjectsReturned,因为slug不是唯一的。我希望URL是
/type/slug/
,因此模型可以包含两个具有相同slug但类型不同的记录,因此URL可以是
/1/slug/
/2/slug/
,结果不同。我如何告诉模型使用类型和slug作为查找,而不仅仅是slug?

您不必“告诉模型”使用类型和字符串字段——您必须覆盖基于类的视图

我建议您重写
get\u queryset
方法,将queryset限制为正确类型的对象。另一种方法是重写
get\u object
方法

class ModelDetailView(DetailView):
    model = MyModel
    template_name = 'detail.html'

    def get_queryset(self):
        """
        Restrict queryset to objects of the correct type
        """
        return MyModel.objects.filter(type_id=self.kwargs['type'])

有关更多详细信息,请参阅上的Django文档。

您不必“告诉模型”使用类型和字符串字段——您必须覆盖基于类的视图

我建议您重写
get\u queryset
方法,将queryset限制为正确类型的对象。另一种方法是重写
get\u object
方法

class ModelDetailView(DetailView):
    model = MyModel
    template_name = 'detail.html'

    def get_queryset(self):
        """
        Restrict queryset to objects of the correct type
        """
        return MyModel.objects.filter(type_id=self.kwargs['type'])
有关更多详细信息,请参阅上的Django文档