Django-一对一模型 [英] Django - one-to-one modelAdmin

查看:85
本文介绍了Django-一对一模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对django有一定的熟练度,并尝试将模型表单用于Intranet项目.

I am moderately proficient with django and trying to use model forms for an intranet project.

基本上,我有一个资源"模型,该模型由另一个团队填充. 第二种模型是"Intake",其中用户提交对资源的请求.它具有与资源的一对一映射.

Essentially, I have a "Resources" model, which is populated by another team. Second model is "Intake", where users submit request for a resource. It has one-to-one mapping to resource.

目标是每次允许只分配1种资源.

Objective is to only allow 1 resource allocation per intake.

现在,摄入量"模型表单将显示该表单,并在资源的下拉字段中显示警告,该表单将显示所有资源,而不管是否进行了先前的分配.

Now, Intake model form shows the form, with a drop-down field to resource, with a caveat that it shows all resources, regardless of previous allocation or not.

例如如果资源被摄入占用,则保存"按钮将检测到不允许进行保存.这是预期的,但是下拉列表不应首先显示该资源.

ex. if resource is taken by an intake, save button detects that disallow saves. This is expected, but then the drop-down should not show that resource in the first place.

我该怎么做,即不显示已分配的资源?

How can I do this, i.e. do not show resource already allocated ?

class Resource(models.Model):
    label = models.CharField(max_length=50, primary_key=True)
    created = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey('auth.User', default=1)

    class Meta:
        verbose_name_plural = "Resource Pool"

    def __str__(self):
        return self.label

class Intake(models.Model):
    order_id = models.AutoField(primary_key=True)
    requestor = models.ForeignKey('auth.User', default=1)
    resource = models.OneToOneField(Resource, verbose_name="Allocation")
    project = models.CharField(max_length=50)

    class Meta:
        verbose_name_plural = "Environment Request"

    def __str__(self):
        print("self called")
        return self.project

推荐答案

您可以在管理员中创建自定义表单,并更改resource字段的queryset值.像这样:

You can create a custom form in your admin and change the queryset value of the resource field. Something like this:

admin.py

from django import forms
from django.db.models import Q

from .models import Intake

class IntakeForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(IntakeForm, self).__init__(*args, **kwargs)
        self.fields['resource'].queryset = Resource.objects.filter(
            Q(intake__isnull=True) | Q(intake=self.instance)
        )

class IntakeAdmin(admin.ModelAdmin):
    form = IntakeForm

admin.site.register(Intake, IntakeAdmin)

这篇关于Django-一对一模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆