Welcome,
I have some problem with limiting choices related with ForeignKey. Below I’m attaching fragment of my code (models.py):
class Car(models.Model):
name = models.CharField(max_length=50)
....
class Driver(models.Model):
name = models.CharField(max_length=50)
car = models.ForeignKey(Car)
....
class CarForm(ModelForm):
class Meta:
model = Car
class DriverForm(ModelForm):
def __init__(self, *args, **kwargs):
super (DriverForm,self).__init__(*args, **kwargs)
self.fileds['car'].queryset = Car.objects.filter(???_1_???)
class Meta:
model = Driver
Could anybody give me some advices how should be defined ???1??? to restrict available Car objects only to these which aren’t assign to any Driver?
First of all, you may want to consider changing the relationship between
CarandDriverto aOneToOneFieldrather than aForeignKeyif eachCarcan always only have a singleDriver.However, if you just want to restrict the choices in the form, your queryset needs to be something like: