Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
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.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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).

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!