0

How can I create a tuple from a model field values?

I have a model CarBrand class, which has a field name called 'name'. How can I create a tuple based on the values of the 'name' field of the CarBrand? class CarBrands(models.Model): name = CharField() I need a tuple like this: carBrands = ( ('Land Cruiser', 'Land Cruiser'), ('Qashqai', 'Qashqai'), )

15th Apr 2020, 6:30 PM
Saidmamad Gulomshoev
Saidmamad Gulomshoev - avatar
3 Respuestas
+ 1
You work with a tuple in a similar way that you would a list, with the major exception of adding and removing elements. Since a tuple is immutable that isn't allowed. Instead you'll need to create a new tuple each time. An easy work around, if you are familar with how to do this with a list, is to convert the tuple to a list(tuple) , make your modificatoins, then convert back to a tuple(list).
15th Apr 2020, 8:18 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
If it doesn't matter which you need to use, and you'll be needing to make changes to it, then I would suggest that you use a list instead of a tuple. If you won't be needing to chnage the elements then use a tuple. I would suggest that you review the section of the python course that covers both lists and tuples. From your question I'm not really sure what exactly you're trying to do. Do you need a static property of the class that will hold all the car model names that are created from each instance? You're already storing the car model otherwise. And what is with the tuple structure in your posted code? Do you need multidimensional tuples that hold the same value in each nested tuple? Given that there are many approaches, a better unedrstanding is desired.
15th Apr 2020, 8:35 PM
ChaoticDawg
ChaoticDawg - avatar
0
ChaoticDawg I do not have neither a tuple nor a list. I have the model CarModel, which has got a field name - "name". So my question is how I can create a tuple or list based on the CarModel.name?
15th Apr 2020, 8:22 PM
Saidmamad Gulomshoev
Saidmamad Gulomshoev - avatar