0

I am trying to learn Django by creating something similar to Reddit. I have models for Post and User, and now I want to create one for "Community". I have looked at this post:

How to store an array of users in django?

However, I am unsure if the ManyToMany relationship is right here (perhaps it is).

I want the Community Model to contain Posts and Users registered with the Community. Each Community can have many posts, and each user can belong to multiple communities. When a Community is deleted, only delete the posts in that community, not the users. Similarly, when a User is deleted or a Post deleted, just remove that aspect from the Community.

If anyone has done this before or knows of a resource to learn this please let me know.

Here is my Post model so far. Note my Communities are called "Bands". Thus all of my references to "Community" will be "Bands" in my project.

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

# each class is its own table in the data
class Post(models.Model):
    # each attribute is a different field in the data
    title = models.CharField(max_length=100)
    content = models.TextField()
    # pass in the function as the default val, but do NOT execute yet!
    date_posted = models.DateTimeField(default=timezone.now)
    # foreign keys link two tables together
    # on delete of User, we delete the user's post as well
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

Here is my Band model:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from home.models import Post

class Band(models.Model):
    name = models.CharField(max_length = 100)
    date_created = models.DateTimeField(default=timezone.now)
    users = (settings.AUTH_USER_MODEL) 

    def __str__(self):
        return "{self.name}"
Steak
  • 514
  • 3
  • 15
  • Hi! You should add your models. Also, what have you tried? Looks like you need a many to many from users to community, and a foreign key from post to community. – gdef_ May 24 '21 at 22:39
  • Yes, I just realized that - sorry! – Steak May 24 '21 at 22:40

0 Answers0