Обновление формы Django с помощью Queryset
У меня есть модель с полем ManyToMany, как показано ниже :
#MODEL
class Car(models.Model):
description = models.CharField(max_length=100, null=True)
is_available = models.BooleanField(default=True, null=True, blank=True)
class Rental(models.Model):
invoice_number = models.CharField(max_length=100, null=True, blank=True)
car = models.ManyToManyField(Car)
И код forms.py :
class RentalUpdateForm(forms.ModelForm):
class Meta:
model = Rental
fields = ['car']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.fields['car'].queryset=Car.objects.filter(is_available=True).all()
Мой вопрос заключается в следующем: как отобразить car на RentalUpdateForm с выбранными текущими значениями, а также отобразить другой автомобиль с условием is_available=True?
Вы можете попробовать что-то вроде этого (в зависимости от используемого виджета формы):
current_cars = self.instance.car.all()
self.fields['car'].initial = [c.pk for c in current_cars]
available_cars = Car.objects.filter(is_available=True).all()
self.fields['car'].choices = [(c.pk, c.description) for c in available_cars]