Devender Shekhawat
Devender Shekhawat

Reputation: 89

Store two types of value in single Django model field

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

Answers (1)

illagrenan
illagrenan

Reputation: 6555

I recommend you to change model schema. Here is suggested model:

Suggested ER 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 UserVotes (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

Related Questions