Python Django模型外键给超级用户
我有一个django模型请求,它有一个字段Approver,设置为具有超级用户状态的用户。我想自动给这个字段赋值,以便它在项目管理员之间轮换。欢迎提出任何建议。提前感谢。我想到的一个简单的解决方案就是在使用请求模型的html模板中,您可以执行一个函数来评估可能的授权用户。。诸如此类: 1.在请求模型中添加一个字段,该字段是用户模型的外键 例如:Python Django模型外键给超级用户,python,django,model,Python,Django,Model,我有一个django模型请求,它有一个字段Approver,设置为具有超级用户状态的用户。我想自动给这个字段赋值,以便它在项目管理员之间轮换。欢迎提出任何建议。提前感谢。我想到的一个简单的解决方案就是在使用请求模型的html模板中,您可以执行一个函数来评估可能的授权用户。。诸如此类: 1.在请求模型中添加一个字段,该字段是用户模型的外键 例如: class Request(models.Model): some other code... assigned_user=models.For
class Request(models.Model):
some other code...
assigned_user=models.ForeignKey(User, on_delete=models.CASCADE)
并在用户模型中添加一个指定的布尔值:
class User(models.Model):
assigned=models.BooleanField(default=False)
然后在创建请求的html代码中:
您可以执行以下操作:
{% for user in Users %}
{% if user.isAdmin %}
{% if not user.assigned %}
<input name="request.varName">{{User.id}}</input>
{% endif %}
{% endif %}
{% endfor %}
我希望在这里有用 您可以将函数作为默认值传递。这样定义一个函数
def default_func():
last_assigned = Request.objects.latest().Approver # gets latest assigned Approver
# the below if statement always looks for the next superuser pk
if User.objects.filter(is_superuser=True, pk__gt=last_assigned.pk).exists():
next_assigned_superuser = User.objects.filter(is_superuser=True, pk__gt=last_assigned.pk)\
.order_by('pk')[0]
# if there isn't a superuser with a higher pk than the last_assigned_superuser, it will choose
# the superuser below or equal to it with the lowest pk. This will handle the case where there is
# only one superuser without any fuss.
else:
next_assigned_superuser = User.objects.filter(is_superuser=True, pk__lte=last_assigned.pk) \
.order_by('pk')[0]
return next_assigned_superuser
并将其添加到您的审批人字段:
# you must pass the function without parenthesis at the end, or else it will
# set the default to whatever the value is at server run time.
# If you pass the function itself, it will be evaluated every time a
# default is needed.
Approver = models.ForeignKey(User, default=default_func)
编辑:将返回值添加到默认函数。哎呀。我在管理表单中编写了一个函数,将审批者设置为请求数量最少的用户。对我来说很好
def get_recipient(self):
approvers = User.objects.annotate(num_of_requests=models.Count('model_field_related_name')).order_by('num_of_requests')
return approvers.first()
欢迎来到StackOverflow。请花点时间阅读这篇文章,以及如何提供答案,并相应地修改你的问题。这些提示可能也很有用。您可以使用模型实例的id除以超级用户使用%的数量,得到余数来选择一个。我想我们可能需要了解一下这是什么样子。可以做的是将它分配给管理员,并且分配给他们的请求最少。但总的来说,这个问题需要更多的信息
def get_recipient(self):
approvers = User.objects.annotate(num_of_requests=models.Count('model_field_related_name')).order_by('num_of_requests')
return approvers.first()