I needed to select multiple items in a models.py (subjects app) which is linked with ForeignKey to another models.py (tutors). I get an error while trying to add items to the database after selecting multiple items in a topics var: "str expects a string but got a list". How do I use the python magic method or some other method in my models.py to return a list of selection and add same to the database?
See below my models.py:
from django.db import models
from multiselectfield import MultiSelectField
# Create your models here.
class Subject(models.Model):
TOPICS = (
('SAT', 'SAT'),
('ACT', 'ACT'),
('GED', 'GED'),
('GRE', 'GRE'),
('READING', 'READING'),
('WRITING', 'WRITING'),
('ESL/ESOL', 'ESL/ESOL'),
('ALGEBRA', 'ALGEBRA'),
('CALCULUS', 'CALCULUS'),
('TRIG', 'TRIG'),
('GEOMETRY', 'GEOMETRY'),
('CHEMISTRY', 'CHEMISTRY'),
('PHYSICS', 'PHYSICS'),
('BIOLOGY', 'BIOLOGY'),
('CODING', 'CODING'),
('STATISTICS', 'STATISTICS'),
('FRENCH', 'FRENCH'),
('SPED', 'SPED'),
)
topics = MultiSelectField(choices = TOPICS,blank=True)
level = models.IntegerField(default=1)
def __str__(self):
return self.topics
Thanks for assisting as I have come to my wits end. Done a lot of research online without luck
self.topics is a list and for string representation you could concatenate list items into string
def __str__(self):
return ','.join(self.topics)
From looking at your models, it seems like you could use a many-to-many relationship instead. See the official django documentation .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.