M
M
Maxim Barabanov2018-04-17 08:46:46
Django
Maxim Barabanov, 2018-04-17 08:46:46

How to make lazy data fetch for form field in admin panel?

There is a ready-made project that has been developing for quite a long time.
And during the development, something like this type of construction appeared in admin.py

class FromCityToCountryDescription_Form(forms.ModelForm):
    from_city = forms.ModelChoiceField(
        queryset=City.objects.filter(id__in=[i.city.id for i in FlyFromCity.objects.all()]),
        label=capfirst(_('fly from city'))
    )

such a queryset definition interferes with migrating to the new development site, since the table from which the selection should be made does not exist
django.db.utils.OperationalError: no such table: burning_tours_flyfromcity

I tried to replace it with a generator - it did not help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2018-04-17
@reb00ter

City.objects.filter(id__in=[i.city.id for i in FlyFromCity.objects.all()])

City.objects.filter(id__in=FlyFromCity.objects.values_list('city_id', flat=True))

The two querysets above are equivalent, although they generate different SQL. The second one is better because at the time of construction it does not require getting all the cities from FlyFromCity. In theory, the issue with migrations will be resolved after that (no requests when importing a module - no problems with migrations)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question