簡體   English   中英

Django模型超級用戶的外鍵

[英]Django model foreign key to Superuser

我有一個Django模型Request,它的字段Approver設置為具有超級用戶狀態的User。 我想自動為該字段分配值,以使其在項目管理員之間輪換。 歡迎任何建議。 提前致謝。

我想到的一個簡單解決方案就是使用請求模型的html模板中,您可以執行一個函數來評估可能的分配用戶..像這樣:1.在請求模型中添加一個外部字段用戶模型的關鍵示例:

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)
  1. 然后在您的html代碼中創建請求:

您可以執行以下操作:

{% for user in Users %}
    {% if user.isAdmin %}
        {% if not user.assigned %}
            <input name="request.varName">{{User.id}}</input>
        {% endif %}
    {% endif %}
{% endfor %}

請記住,您必須在視圖中調用請求模型和用戶模型。您可以通過以下方式實現此目的:

class RequestCreate(CreateView):
    ... some other code..
        def get_context_data(self, **kwargs):
            context = super(RequestCreate, self).get_context_data(**kwargs)
            context['Users'] = User.objects.all()
            #context['venue_list'] = Venue.objects.all()
            #context['festival_list'] = Festival.objects.all()
            # And so on for more models
    return context

我希望在這里有用。

您可以將函數作為默認值傳遞。 像這樣定義一個函數

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)

編輯:將返回值添加到default_func。 哎呀

我在Admin表單中編寫了一個函數,該函數將批准者設置為請求數量最少的User。 對我來說很好。

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM