Reputation: 89
I am learning django by creating a polling application. For starters I have three models User, Question and Choices.
class User(....):
....
Questions_voted = models.ManyToManyField(Question)
....
this means that a user to vote for as many questions as he wants. Next is The Question Model which is simple and just store question text and number of people voted for it.
class Question(models.Model):
question_text = models.CharField(max_length=500)
vote_count = models.IntegerField(...)
next is Choices which have a choice_text and refers to the question it belongs to.
class Choice(models.Models):
choice_text = models.CharField(models.Model)
question = models.ForeignKey(Question,...)
Now I want to store information about what choice a user selected for a question. It is very clear when you think of it but I am stuck because of lack of knowledge of types of fields in django models.
Upvotes: 1
Views: 650
Reputation: 6555
I recommend you to change model schema. Here is suggested model:
I added UserVote
model that holds information about Question
and Choice
selected by User
.
from django.conf import settings
class UserVote(models.Model):
question = models.ForeignKey('Question')
choice = models.ForeignKey('Choice')
user = models.ForeignKey(settings.AUTH_USER_MODEL)
EDIT: How to read suggested schema: User
can have many UserVote
s (there is Many-To-One
relation – in Django you simply add ForeignKey
to UserVote
). Each UserVote
must have one-and-only one Question
and Choice
. The rest is your old schema. Btw I used Crow's foot notation (https://en.wikipedia.org/wiki/Entity%E2%80%93relationship_model#Crow.27s_foot_notation).
Upvotes: 2