I got a Model "PC_Configuration" with a bunch of Dropdown-Lists:
class PC_Configuration(models.Model):
PROCESSOR_CHOICES = (
('None', 'Wähle deinen Prozessor'),
('1', 'Prozessor1'),
('2', 'Prozessor2'),
('3', 'Prozessor3'),
)
GRAPHICSCARD_CHOICES = (
('None', 'Wähle deine Grafikkarte'),
('1', 'Grafikkarte1'),
('2', 'Grafikkarte2'),
('3', 'Grafikkarte3'),
)
OS_CHOICES = (
('None', 'Wähle dein Betriebssystem'),
('1', 'Betriebssystem1'),
('2', 'Betriebssystem2'),
('3', 'Betriebssystem3'),
)
RAM_CHOICES = (
('None', 'Wähle deinen Arbeitsspeicher'),
('1', 'RAM1'),
('2', 'RAM2'),
('3', 'RAM3'),
)
HARDDRIVE_CHOICES = (
('None', 'Wähle deine Restspeicher-Größe'),
('1', 'Festplatte1'),
('2', 'Festplatte2'),
('3', 'Festplatte3'),
)
processor = models.CharField(max_length=25, choices=PROCESSOR_CHOICES, default='None')
graphicscard = models.CharField(max_length=25, choices=GRAPHICSCARD_CHOICES, default='None')
ram = models.CharField(max_length=25, choices=RAM_CHOICES, default='None')
os = models.CharField(max_length=25, choices=OS_CHOICES, default='None')
harddrive = models.CharField(max_length=25, choices=HARDDRIVE_CHOICES, default='None')
I just tested the Choices of those Dropdown-Fields with some Hardcoded Inputs, but I actually want to get all Data for the Choices of e.g. the "processors"-Dropdown-Field from the Table of the field name of the Model Processors:
class Processors(models.Model):
name = models.CharField(max_length=50)
So my question is: Is it possible to get all the values inside the name-Fields of the Processors-Model, maybe write them into a Array just like the current Hardcoded Input for being able to show them inside the Dropdown-Field of the PC_Configuration Model?
Short Edit: I've tried to use something like:
list(PC_Configuration.objects.all().values_list('name', flat=True))
But it seems like "PC_Configuration.objects" isn't existing..
CodePudding user response:
You can have a ForeignKey to that table in your model lets say:
processor = models.ForeignKey(Processors, models.DO_NOTHING)
Than you can create a model form for PC_Configuration
class MyForm(forms.ModelForm):
class Meta:
model = PC_Configuration
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['processors'].quereset = Processors.objects.all()
self.fields['processors'].label_from_instance = lambda obj: "%s" % obj.name