Django:如何创建一个由给定外键分组(排名)的辅助ID字段?
输出可能看起来像这样,例如:
ID | Secondary_id | FK |
---|---|---|
1 | 1 | 1 1 |
2 | 2 | 1 |
3 | 3 | 1 |
4 | 1 | 2 |
5 | 2 | 2 |
在上下文中:(
请参见下面的模型)
我有一个佣金结构,该结构将取决于多少用户一个月内收入。 理想情况下,我需要在我的佣金支架模型中知道,这是给定结构的支架索引。
这是我的模型。
class CommissionStructure(APIBaseModel):
advisor = models.ManyToManyField(AdviserDetail)
name = models.CharField(max_length=20, blank=True, null=True, default='default')
company = models.ForeignKey(Company, on_delete=models.CASCADE)
start_dt = models.DateTimeField(auto_now_add=True)
end_dt = models.DateTimeField(default=timezone.datetime.max)
objects = CommissionStructureManager()
class CommissionBracket(APIBaseModel):
<secondary_id ???>
commission_structure = models.ForeignKey(CommissionStructure, on_delete=models.CASCADE, related_name="brackets")
lower_bound = models.DecimalField(decimal_places=2, default=0.00, max_digits=20, null=True, blank=True)
upper_bound = models.DecimalField(decimal_places=2, default=0.00, max_digits=20, null=True, blank=True)
请注意,如果可以在聚合套件中添加注释,我可能不必将其存储在模型上,但我的偏爱是擦干。
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的建议是。您可以将辅助ID添加为
commissionBracket
中的整数字段。然后,您可以实现以下内容:在这里我们使用 ins select 从同一表中基于新记录的
secondary_id
。我们还添加a case ,以便我们可以在没有记录的情况下拥有后退值使用commission_structure_id
值返回1。如果您需要在创建过程中填充其他列,则可以简单地将它们包括在内:
My suggestion would be to execute custom SQL directly. You can add the secondary id as an integer field in
CommissionBracket
. Then, you can implement this:Here we're using INSERT INTO SELECT since we're basing the new record's
secondary_id
from the same table. We're also adding a CASE so that we can have a fallback value if no record withcommission_structure_id
value as 1 is returned.In case you need to populate other columns during create, you can simply include them like so:
我找到了一种注释QuerySet的方法,但是为了兴趣,我最初的问题仍然存在:如何添加外键分区的另一个字段?
I've found a way to annotate the queryset, but for interest, my original question still remains: how do I add another field partitioned by the foreign key?