Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Choices based on Foreign Key

I am wondering if there is a way to use a list that is stored in a foreignkey as the choices for a charfield.

Here is what I have right now but it is not working.

priority = models.ForeignKey(SLAs)
prioritylevel = models.CharField(choices=priority.details)

It says that the ForeignKey has no attribute 'details'

If this has been answered, please point me the correct direction.

Thanks :)

like image 667
icebox3d Avatar asked Nov 06 '25 09:11

icebox3d


1 Answers

I think you want use this in forms?

So you can do smth like this:

class MyForm(forms.ModelForm):
    prioritylevel = forms.ModelChoiceField(queryset=OtherModel.objects.values('level'))

and in model this will just CharField. It this solve your problem?

like image 121
Andrey Nelubin Avatar answered Nov 08 '25 07:11

Andrey Nelubin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!