Dynamic Drop List for Many to Many relation

332 Views Asked by At

I have 2 tables "Client" and "Location".

class Client(models.Model):
    name = models.CharField(max_length=50)

class Location(models.Model):
    name = models.CharField(max_length=50)

A Client can be in many Locations and a Location can have many Clients.

I created a third table to hold this relationship:

class Client_Location(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    location = models.ForeignKey(Location, on_delete=models.CASCADE)

I created a form to test whether i can make the dropdownlist dynamic, so if i were to pick a client, any location linked to that client would only appear.

class ClientLocationForm(forms.ModelForm):
    class Meta:
        model = Client_Location
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['location'].queryset = Location.objects.none()

So far i was only able to make the location field blank. Not sure where to go next as examples i've seen aren't exactly like mine.

1

There are 1 best solutions below

4
On

With minimal changes to your code, you may add the existing Client_Location model as through model for a new explicit ManyToMany relationship. To do so, add the following field to your Client model:

 locations = models.ManyToManyField('Location', through='Client_Location', related_name='clients')

If you need fully dynamic updates, you need to write a view which provides a list of locations for a specified client (client.locations.all()) and then show them on your page.