如何根据外键范围设置django对象的主键范围,是否可取?

How to set the range of the primary-key of django objects based on the foreign key range and is it advisable?

我有以下型号:

class Author(model):
    name = CharField(...)

class Post(mode):
    author = ForeignKey(Author)
    title = CharField(...)

假设我们最多有 100 位作者。所以 autors 的主键将在 1 到 100 的范围内 我希望 post 模型的主键基于 post.

作者的主键

我的意思是,如果作者的主键是34,那么his/her post的主键就是34000001, 34000002, 34000003

建议这样做,我该怎么做?

这通常是不可取的,并且可能会诱使您遵循(或发明)反模式。例如,如果您的目标是能够轻松访问特定作者的帖子,那么使用 Django 的常规 ORM 模式是最安全的。例如:

# models.py
class Author(model):
    name = CharField(...)

class Post(model):
    author = ForeignKey(Author, related_name='posts')
    title = CharField(...)

然后你可以在任何地方...

sally = Author.objects.get(id=1)
sallys_posts = author.posts.all()

这比您可能想做的事情要安全得多,例如 Post.objects.filter(pk__startswith=sally.pk) 我认为这会导致大量错误,并且也意味着你错过了很多正常模式 Django ORM 的好处。