[Answered ]-Django admin onetoone field

2👍

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)

Leave a comment