Single dropdown with values from two tables

  Kiến thức lập trình

I may be going about this entirely wrong. I’m new to Django, so sometimes the way I think of things doesn’t seem to be the easy Django way to do it.

I’ve got two tables:

class LocationGroup(models.Model):

    #Fields
    ##Location Group ID - auto generated ID field
    id = models.AutoField('Location Group ID', primary_key = True)
    ##Location Group Name
    name = models.CharField('Location Group Name', max_length=200, help_text='Location Group name')
    def __str__(self):
    """String for representing the Model object."""
    return self.name

    class Meta:
        verbose_name = "Location Group"
        verbose_name_plural = "Location Groups"

and

class Location(models.Model):

    #Fields
    ##Location ID - auto generated ID field
    id = models.AutoField('Location ID', primary_key = True)
    ##Location name
    name = models.CharField('Location Name', max_length=200, help_text='Location name')
    ##Location Group - link location to a Location Group
    group = models.ManyToManyField('LocationGroup', verbose_name='Location Group', blank=True, help_text='...')
...etc

Then I have my forms.py calling as follows:

class MyForm(forms.ModelForm):
    class Meta:
        model = Call
        fields = ['location', ...etc]

This all works well and I can pick a location and add it to the database with the other values that are on that form/model. But what I’d like to do, is include the values from the locations plus the location groups.

And to go further, if a value is picked that was from the location groups, I need to enter a record in the database for each location contained in that group along with all the other values on the form.

I’m sure it would be easier to just have two forms depending on if you want to pick a location or a group. But, if possible, I’d really like to simplify the interface this way.

LEAVE A COMMENT