user3772883
user3772883

Reputation: 23

Define models in Django

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'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

Answers (2)

aldo_vw
aldo_vw

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

pseudonym117
pseudonym117

Reputation: 839

To do this, I would recommend breaking down each individual relationship. Your relationships seem to be:

  1. Authoring
  2. Following

For authoring, the details are:

  • Each Question is authored by one User
  • Each User can author many questions

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:

  • Each Question can have many following Users
  • Each User can be following many Questions

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

Related Questions