Два примера только немного отличаются:
Первый:
class ScanInlineAdmin(admin.TabularAdmin):
model = Scan
formset = ScanInlineFormset
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "visit":
patient = self.get_object(kwargs['request'], Patient)
kwargs["queryset"] = Visit.objects.filter(patient=patient)
return super(ScanInlineAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
def get_object(self, request, model):
object_id = request.META['PATH_INFO'].strip('/').split('/')[-1]
try:
object_id = int(object_id)
except ValueError:
return None
return model.objects.get(pk=object_id)
Второй:
class ScanInline(admin.TabularInline):
model = Scan
formset = ScanInlineFormset
def formfield_for_dbfield(self, field, **kwargs):
if field.name == 'visit':
# Note - get_object hasn't been defined yet
patient = self.get_object(kwargs['request'], Patient)
vists = Visit.objects.filter(patient=patient)
return forms.ModelChoiceField(queryset=visits)
return super(ScanInline, self).formfield_for_dbfield(field, **kwargs)
def get_object(self, request, model):
object_id = request.META['PATH_INFO'].strip('/').split('/')[-1]
try:
object_id = int(object_id)
except ValueError:
return None
return model.objects.get(pk=object_id)
Вам может пригодиться эта статья .Я предполагаю, что на странице пациента администратор редактирует / просматривает, где вы хотите ввести новое сканирование.Это правильно?