如何在Django中创建具有惟一ID并在重复键上递增的表

时间:2022-11-25 14:09:05

I'm kind of new to Django and I've hit a bit of a wall with building out the project.

我对Django有点陌生,我在项目的构建过程中遇到了一些问题。

Essentially, I have two tables. Projects and Entries. Users create projects, then add entries to each project. Entries has an auto_increment ID, and a column for project_Id to specify which project owns the entries, but the entry ID increments site-wide. I would like to have entries increment on a per-project basis, so that the first Entry a user creates in their Project will always be 1, and the 2nd Entry will be 2, etc.

本质上,我有两个表。项目和条目。用户创建项目,然后向每个项目添加条目。条目有一个auto_increment ID,以及一个project_Id列来指定哪个项目拥有条目,但是条目ID在站点范围内递增。我希望每个项目都增加一个条目,这样用户在项目中创建的第一个条目将永远是1,第二个条目将是2,等等。

Can I do this in models.py? For example, in:

我可以用model .py吗?例如,在:

class Entries(models.Model):
    project_id = models.ForeignKey(Projects)

can I create another line (say, entry_unique) that will tell it to create another column that increments +1 when project_id and entry_unique are the same as a previous table entry?

如果project_id和entry_unique与之前的表条目相同,我是否可以创建另一行(例如,entry_unique),告诉它创建另一个增加+1的列?

It's very important that each entry gets a visible (to user) entry ID # that increments +1 each time they create a new entry for that project, and that they be able to navigate through their entries by going +1 or -1 via "forward" and "backward" URLs.

很重要的一点是,每个条目都有一个可见的(对用户)条目ID #,每次为该项目创建一个新条目时,该ID #都增加+1,并且它们能够通过“向前”和“向后”url导航它们的条目。

1 个解决方案

#1


1  

You can override the model Entry's save method to accomplish what you want to do:

你可以重写模型条目的保存方法来完成你想做的事情:

class Entries(models.Model):
    project_id = models.ForeignKey(Projects)

    def save(self, *args, **kwargs):
        user = kwargs.pop('user')
        project = kwargs.pop('project')

        latest = Entries.objects.filter(user=request.user, project_id=project)
        latest_entry = latest.entry_unique if latest else 1         
        self.entry_unique = latest_entry

        super(Entries, self).save(*args, **kwargs)

Now, wherever you reference the project id, for a user, you can reference entry.entry_unique

现在,无论您在何处引用项目id,对于用户,都可以引用entry_unique

Read up about latest() here

在这里阅读有关latest()的文章

#1


1  

You can override the model Entry's save method to accomplish what you want to do:

你可以重写模型条目的保存方法来完成你想做的事情:

class Entries(models.Model):
    project_id = models.ForeignKey(Projects)

    def save(self, *args, **kwargs):
        user = kwargs.pop('user')
        project = kwargs.pop('project')

        latest = Entries.objects.filter(user=request.user, project_id=project)
        latest_entry = latest.entry_unique if latest else 1         
        self.entry_unique = latest_entry

        super(Entries, self).save(*args, **kwargs)

Now, wherever you reference the project id, for a user, you can reference entry.entry_unique

现在,无论您在何处引用项目id,对于用户,都可以引用entry_unique

Read up about latest() here

在这里阅读有关latest()的文章