ilnurgi
ilnurgi

Reputation: 13

django admin onetoone field

class Model1(models.Model):
  name = models.CharField(...)
  ...
class Model2(models.Model)
  model = models.OneToOneField(Model1)
  ...

I go to the admin panel. page add an entry to Model2, watch list model. And there all the records from Model1. Is it possible to customize the admin area so that the list did not get records that already have a relationship.

thank you

Upvotes: 1

Views: 479

Answers (1)

Prashant Gaur
Prashant Gaur

Reputation: 9828

You Should override _init_ method of form class. You can take help from below given code.

from django import forms
from .models import Model2, Model1

class Model2Form(forms.ModelForm):
    model1 = forms.ModelChoiceField(queryset=[],)

    class Meta:
        model = Model1

    def __init__(self, *args, **kwargs):
        """ initialize form data """
        super(Model2Form, self).__init__(*args, **kwargs)
        model2_obj = Model2.objects.all().values_list('model1')
        model2_list = [data[0] for data in model2_obj]
        self.fields['model1'].queryset = Model1.objects.exclude(id__in=model2_list)

In admin.py.

from django.contrib import admin

from .forms import Model2Form
from .models import Model2

class Model2Admin(admin.ModelAdmin):
    form = Model2Form
    fields = ['model1']
admin.site.register(Model2, Model2Admin)

Upvotes: 2

Related Questions