Search code examples
pythondjangodjango-queryset

django conditional filtering


I have this model of Vehicle:

class Vehicle(models.Model):
    ...
    driver = models.OneToOneField(Driver, related_name="vehicle", on_delete=models.CASCADE,
                                  blank=True, null=True)

In my form i want to initialize the queryset of driver so only the driver that have no relations with vehicle appear in list (because its one-to-one relations). So in my forms.__init__:

self.fields['driver'].queryset = vendor.drivers.select_related('user').filter(vehicle__isnull=True)

but I realize in my edit form (using ModelForm), the driver not initialized in form because i guess, the queryset override it. The initial driver is not vehicle__isnull

So what i want is, vehicle__isnull except for this initial driver if there is a driver already. How can I achieve that? Any help would be appreciated.


Solution

  • You can try like this:

    class YourForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
           super().__init__(*args, **kwargs)
           ...
           drivers = vendor.drivers.select_related('user').filter(vehicle__isnull=True)
           if self.instance and self.instance.pk:
                 drivers |= Driver.objects.filter(pk=self.instance.driver.pk)
           self.fields['driver'].queryset = drivers
    

    Here, I am checking if there is any instance of the form exists, that means it is in edit mode. If yes, I am combining the existing driver with the queryset. More information can be found in the documentation.