Django - one-to-one modelAdmin

可紊 提交于 2019-12-22 17:38:12

问题


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

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.

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


回答1:


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)



回答2:


You could probably use limit_choices_to on the field definition:

resource = models.OneToOneField(Resource, verbose_name="Allocation",
                                limit_choices_to={'intake__isnull': True})


来源:https://stackoverflow.com/questions/43940563/django-one-to-one-modeladmin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!