Django DB 设计 - 使用 unique_together 预订特定的唯一 URL



我有两个一对多关系的模型。

  • 一个Book有很多Chapter。两个模型都有一个slug字段。

  • 对于BookslugUNIQUE

  • 对于Chapter来说,book_idslugUNIQUE在一起的。

  • Chapter模型也有一个字段orderbook_idorderUNIQUE在一起。

这样,我可以自动为书籍生成唯一的 URL,并允许不同书籍的重复 slug。

当前models.py

class Book(models.Model):
# other fields
slug = models.SlugField(max_length=80)
def save(self, *args, **kwargs):
if not self.pk:
self.slug = unique_slug(self.title)  
return super(Book, self).save(*args, **kwargs)

class Chapter(models.Model):
#other fields
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='chapters')
slug = models.SlugField(max_length=80)
order = models.IntegerField(null=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=['book_id', 'order'], name='unique_order'),
models.UniqueConstraint(fields=['book_id', 'slug'], name='unique_slug')]
ordering = ['order']

图书应用urls.py

urlpatterns = [
# Book
path('', views.BookList.as_view(), name='book-list'),
path('create/', views.BookCreate.as_view(), name='book-create'),
path('<slug:book_slug>/', views.BookDetail.as_view(), name='book-detail'),
path('<slug:book_slug>/edit/', views.BookEdit.as_view(), name='book-edit'),
# Chapter
path('<slug:book_slug>/chapter/', views.BookDetail.as_view(), name='chapter-list'),    
path('<slug:book_slug>/chapter/create/', views.ChapterCreate.as_view(), name='chapter-create'),
path('<slug:book_slug>/chapter/<slug:chapter_slug>/', views.ChapterDetail.as_view(), name='chapter-detail'),
path('<slug:book_slug>/chapter/<slug:chapter_slug>/edit/', views.ChapterEdit.as_view(), name='chapter-edit')
]   

这里的缺点是,在我的chapter观点中,我必须先查询这本书,然后获得具有匹配book_id的章节slug。虽然以前只有章节slugUNIQUE,但我只是单独查询章节表。


我的目标是拥有这样的网址

  1. book/rndmstrng-alice-in-the-wonderland/chapter/down-the-rabbit-hole

  2. book/rndmstrng-some-other-book/chapter/down-the-rabbit-hole


这个设计有什么问题吗?太多的UNIQUE约束不好吗?有没有更好的方法来实现这一点?

您可以使用两个 slug 覆盖get_object进行查询,并使用select_related在单个查询中获取这两个对象

def get_object(self, queryset=None):
return get_object_or_404(Chapter.objects.filter(
book__slug=self.kwargs['book_slug'],
slug=self.kwargs['chapter_slug']
).select_related('book'))

您的表格设计看起来不错,可以进行一些细微的改进

SlugField默认为db_index=True,因为通常查询 slug 字段,UniqueConstraint也会在传递给它的字段上创建索引。这意味着您有两个包含 slug 字段的索引,您可以通过删除字段上的索引并更改UniqueConstraint的顺序使其减少到一个,以便 slug 字段排在第一位(索引中字段的顺序很重要,您通常需要"更唯一"的字段,或者在没有其他字段的情况下进行查询(

class Chapter(models.Model):
# Other fields
slug = models.SlugField(max_length=80, db_index=False)
class Meta:
constraints = [
# Other constraints
models.UniqueConstraint(fields=['slug', 'book'], name='unique_slug')
]

最新更新