0

I am confused of defining OneToMany relation in django which is not in Django. ManyToOne field can be done using ForeignKey but i dnt have idea to define for OneToMany.

here is my problem, I want to add Users as a list to a model.

Class Post(models.Model):
    postcontent =  models.CharField(max_length=2000)
    votedusers = ???  # list of users who voted

Simply it should lists the Users who voted a Post. How to achieve this ?? Thanks in advance.

Wickkiey
  • 4,446
  • 2
  • 39
  • 46

2 Answers2

1

It should be the many-to-many relation:

Class Post(models.Model):
    postcontent =  models.CharField(max_length=2000)
    votedusers = models.ManyToManyField(User)
catavaran
  • 44,703
  • 8
  • 98
  • 85
-2

You cant see the docs here: Django Docs

This is a example:

from django.db import models

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

def __str__(self):              # __unicode__ on Python 2
    return "%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter)

def __str__(self):              # __unicode__ on Python 2
    return self.headline

class Meta:
    ordering = ('headline',)

In your case should be:

Class Post(models.Model):
    postcontent =  models.CharField(max_length=2000)
    votedusers = models.ForeignKey(Users)  # list of users who voted