Фильтрация по выбору и удаление, если они уже присутствуют в базе данных

посмотрите на картинку, прежде чем отвечать мне. эта группа2 внутри сохранена в базе данных с помощью кнопки я открываю модал, который позволяет мне сохранить другие группы в базе данных, и я хотел бы, чтобы те же группы больше не появлялись в этом селекте, если я уже добавил их

enter image description here

Вы можете переопределить поле формы перед ее инстанцированием следующим образом :

views.py

from django import forms

if request.method == "POST":
    # Post logic here
else:
    
    # We try to retrieve group that the current user is not yet in.
    # Not your logic, but to sum up, you have to retrieve the groups
    # which had not yet been added.
    # Use a filter that permit you to retrieve only groups which had not yet been added.
    group_to_add = Group.objects.filter(...)
    GruppiForm.base_fields['group_field'] = forms.ModelChoiceField(
        queryset=group_to_add)

# Instantiate the form now
# In this form, the choices are only those contained in the group_to_add queryset
form = GruppiForm(prefix = 'gruppo')
Вернуться на верх