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文档