0

我有一个模型

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})

和网址

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

和一个 DetailView

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

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

4

1 回答 1

3

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

我建议您重写该get_queryset方法,以将查询集限制为正确类型的对象。另一种方法是覆盖该get_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 文档。

于 2013-04-20T16:06:14.583 回答