Reputation: 23
I'm new to Django and I'm trying to create a simple app!
I basically want to create something like StackOverflow, I have many User
and many Question
. I don't know how I should define the relationship between these two Models.
My Requirements:
I want each Question
to have a single author User
, and a list of User
that followed the Question
.
I want each User
to have a list of posted Question
and a list of followed Question
.
I'm pretty much lost, and I don't know how to define my relationship. Is this a many-to-many relationship? If so, how do I have like 2 lists of Question
in my User
model (Posted/Followed)?
Please help!
Upvotes: 2
Views: 112
Reputation: 638
A very basic model to get you started:
models.py
from django.db import models
from django.contrib.auth.models import User
class Question(models.Model):
question = models.CharField(max_length=200)
user = models.ForeignKey(User)
def __unicode__(self):
return self.question
class Following(models.Model):
question = models.ForeignKey(Question)
user = models.ForeignKey(User)
Upvotes: 1
Reputation: 839
To do this, I would recommend breaking down each individual relationship. Your relationships seem to be:
For authoring, the details are:
As such, this is a One-to-Many relationship between the two. The best way to do this is a foreign key from the Question to the User, since there can only be one author.
For following, the details are:
As such, this is a Many-to-Many relationship. The Many-to-Many field in Django is a perfect candidate for this. Django will let you use a field through another model, but in this case this is not needed, as you have no other information associated with the fact that a user is following a question (e.g. a personal score/ranking).
With both of these relationships, Django will create lists of related items for you, so you do not have to worry about that. You may need to define a related_name
for this field, as there are multiple users associated with a question, and by default django would make the related set for both named user_set
.
Upvotes: 3