Storing multiple select values in django

419
August 30, 2017, at 10:14 PM

I am a fresher in Django. I was searching for a article or SO thread describing the way django stores multiselect list box values in the database but couldn't find one.

In my case I have categories list box with options for example(C1,C2,C3). The category name can be a long one. I want to assign multiple categories to single user. It can be single category assigned to a user as well.

My model will look like this(cat_name fiels depends on how it stores in the db)

class Category(models.Model):
    user = models.ForeignKey(User)
    cat_name = models.CharField(max_length=100)
    #or cat_name = models.TextField()

My question is how django will store the values in the db

id    user_id    cat_name
1     1          C1&C2&C3
2     2          C1&C2
3     3          C3

Or

id    user_id    cat_name
1     1          C1
2     1          C2
3     1          C3
4     2          C1
5     2          C2
6     3          C3

If it's the first case then I'll use TextField else CharField. & used in the first case is just an example.

Any suggestion/link is highly appreciated. Thanks in advance.

Answer 1

Django will store your data as a string.

Say you have a MultipleChoiceField called cat_name in your ModelForm and have a defined schema for the field is a CharField.

Django has the form value as a list before it is saved. When you save it, the field's python value gets converted to its corresponding db value during a call to get_prep_value.

>>> selection = ['cat 1', 'cat 2', 'cat 3']
>>> str(selection)
"['cat 1', 'cat 2', 'cat 3']"

Trouble with this:

  • You have to teach Django how to convert back to_python.
  • You are duplicating data across rows.
Answer 2

you may try this

cat_name = models.CharField(max_length=255, validators=
[validate_comma_separated_integer_list], null=True)

store multiselect values for field

Rent Charter Buses Company
READ ALSO
Parameter is not correct in python

Parameter is not correct in python

In the above code what is wrong, when i ran getting parameter is wrongPls help Error:Parameter format not correct - "sC:\Users\gnk\Desktop\stg"

389
QGraphicsScene changing objects when selected

QGraphicsScene changing objects when selected

I have a QGraphicsScene containing some simple objects (in this case circles) that I want to change into squares when selectedMore generally I'd like to have parent objects which don't draw themselves: they are drawn by their child objects

353
Python django error

Python django error

am new to python and django

474