Django has a unique_for_date property you can set when adding a SlugField to your model. This causes the slug to be unique only for the Date of the field you specify:
Django有一个unique_for_date属性,您可以在向模型添加SlugField时设置该属性。这会导致slug仅对您指定的字段的Date具有唯一性:
class Example(models.Model):
title = models.CharField()
slug = models.SlugField(unique_for_date='publish')
publish = models.DateTimeField()
What would be the best way to achieve the same kind of functionality for a non-DateTime field like a ForeignKey? Ideally, I want to do something like this:
对于像ForeignKey这样的非DateTime字段,实现相同功能的最佳方法是什么?理想情况下,我想做这样的事情:
class Example(models.Model):
title = models.CharField()
slug = models.SlugField(unique_for='category')
category = models.ForeignKey(Category)
This way I could create the following urls:
这样我就可以创建以下URL:
/example/category-one/slug
/example/category-two/slug
/example/category-two/slug <--Rejected as duplicate
My ideas so far:
我的想法到目前为止:
Add a unique index for the slug and categoryid to the table. This requires code outside of Django. And would the built-in admin handle this correctly when the insert/update fails?
将slug和categoryid的唯一索引添加到表中。这需要Django之外的代码。当插入/更新失败时,内置管理员会正确处理吗?
Override the save for the model and add my own validation, throwing an error if a duplicate exists. I know this will work but it doesn't seem very DRY.
覆盖模型的保存并添加我自己的验证,如果存在重复则抛出错误。我知道这会起作用,但看起来不是很干。
Create a new slug field inheriting from the base and add the unique_for functionality there. This seems like the best way but I looked through the core's unique_for_date code and it didn't seem very intuitive to extend it.
创建一个继承自base的新slug字段,并在那里添加unique_for功能。这似乎是最好的方法,但我查看了核心的unique_for_date代码,并且扩展它似乎不太直观。
Any ideas, suggestions or opinions on the best way to do this?
有关最佳方法的任何想法,建议或意见?
14
What about unique_together?
那么unique_together怎么样?
class Example(models.Model):
title = models.CharField()
slug = models.SlugField(db_index=False)
category = models.ForeignKey(Category)
class Meta:
unique_together = (('slug','category'),)
# or also working since Django 1.0:
# unique_together = ('slug','category',)
This creates an index, but it is not outside of Django ;)
Or did I miss the point?
这会创建一个索引,但它不在Django之外;)或者我是否忽略了这一点?
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2010/01/31/e38bdb830bb273e5781f673cf9c48901.html。