Reputation: 329
I have the following models:
class Name(models.Model):
device_type = models.CharField('Device Type', max_length=30, blank=True, null=True)
class Device(models.Model):
DEVICE_TYPE_CHOICES = (
('Router', 'Router'),
('Switch', 'Switch'),
('Firewall', 'Firewall'),
('Load Balancer', 'Load Balancer'),
)
device_name = models.CharField('Device Name', max_length=100)
device_type = models.CharField('Device Type', max_length=20, blank=True, null=True, choices=DEVICE_TYPE_CHOICES)
Given the above, right now when I create a new object using my Device model, choices for device_type are defined statically using the Field.choices method and this shows up in Django Admin as a drop down list with the four choices shown.
What I really want is to have that list of choices defined dynamically based on the following concept which basically says "from the Name model/table return a list of all values found in the 'device_type' column":
Name.objects.all().values_list('device_type')
I'm just not sure how to put this into practice. I'm not sure how to take the list which I already know how to get from my database and incorporate it into the Field.objects method so that those items show up as choices in my drop down menu.
Can anyone point me in the right direction? Thanks in advance for any assistance.
UPDATE AFTER FOREIGN KEY FIX:
Now my models look like this:
class Name(models.Model): # device type naming standards
device_type = models.CharField('Device Type', max_length=30, blank=True, null=True)
device_alias = models.CharField('Device Alias', max_length=30, blank=True, null=True)
def __unicode__(self):
return self.device_type
class Device(models.Model):
location_name = models.ForeignKey('Location')
device_name = models.CharField('Device Name', max_length=100)
device_type = models.ForeignKey('Name')
#device_type = models.CharField('Device Type', max_length=20, blank=True, null=True, choices=DEVICE_TYPE_CHOICES)
Now you'll see in my Device model I have two ForeignKeys. I need Location to be a ForeignKey because I want to put Devices categorically under a specific Location. I need the device type ForeignKey per my previous question. When I have two ForeignKeys like this, when I go to my Device table in Django Admin, I see no devices (even though they were in the table before I created the device_type ForeignKey. If I comment out the device_type ForeignKey and uncomment out the last line to go back to what I had before (after updating the schema with 'makemigrations' and 'migrate', now the devices show up again. Obviously I need the devices to show up in my device table. Am I allowed to have multiple ForeignKeys? I'm sure I'm not understanding something critical here.
Upvotes: 0
Views: 1964
Reputation: 2212
If you will use ForeignKey, you'll get the list of name devices
device_type = models.ForeignKey('Name')
def __unicode__(self):
return self.device_type
Hope it help you.
Upvotes: 1