How to save a value instead of primary key in foreign key based dropdown in database

When using a foreign key to provide a dropdown to user in model form how can we save the dropdown value in the database rather than the primary key

If the field being saved is a foreign key, you don’t want to save a value, you need to save the key.

If the field isn’t a foreign key, we’ll need to see the view, form, and model being saved to properly advise you.

Hi KEn,
Thanks for the reply. i am looking for a value as i found that when i want to view the data back using querysets it displays id’s instead of the actual value. also i tried alternative my declaring my model field as char and used a queryset and modelchoicefield to make it a dropdown. but in my project i am trying to make a system where the user can clone a existing database row back into the form using(form instance and edit and resubmit) when i used char and model choice field the dropdowns dont get populated

That’s an issue then of how you’re displaying the value, not an issue of needing to save the value in your model.

Hi Ken,

So if i want to display the value instead of the ID when i filter data using queryset what should be done!! Relativley new to django sorry if its a silly question

See the docs and examples at Many-to-one relationships | Django documentation | Django,

Also see The Django template language | Django documentation | Django

If you need more specific or targeted assistance, please post the model(s) and one of the templates involved - it’ll make providing a description a lot easier.

Hi Ken,

Thanks for the help i got the solution. your earlier answer made me think differently . earlier i was figuring out how to save value now i started hunting how to display foreign key value in template and got solution

this post helped me

i ended up using (program__program) in my queryset to display data of foreign key

That question and the related answers are dangerously old and no longer “best practice” or even “common practice”.

Please, do yourself a favor and do not rely upon SO for code samples. (Or for any Django-related information, for that matter.) You’re going to pick up a lot of bad habits along the way.

thanks for the tip Ken will keep it in mind going forward