简体   繁体   中英

Create a one to many relationship with Django

Hey guys I'm making a social media app and I have a User table with the generic User Model from Django used.

I'm now creating a Follow table where I want to keep track of the different usernames the user follows and a count of those following him (I don't need to display the names for the followers field just the amount of followers a user has).

How would I go about doing this? Right now this is what I have, but I'm unable to view the actual data in the database so I'm not sure how it works. Is there a column for username that is borrowed from the User model? I can't find solid information on how this works.

    from django.contrib.auth.models import AbstractUser
from django.contrib.postgres.fields import ArrayField
from django.db import models

class User(AbstractUser):
    pass
    
class Follow(models.Model):
    followers = models.IntegerField(default=0)
    following = models.ForeignKey(User, related_name = 'follow_to_set', on_delete = models.CASCADE)

class NewPost(models.Model):
    username = models.CharField(max_length=64)
    body = models.CharField(max_length=64)
    likes = models.IntegerField(default=0)
    timestamp = models.DateTimeField(auto_now_add=True)

You can try this way:

models.py

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

class Profile(models.Model) :
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_profile")
    followers = models.IntegerField(default=0)

    def __str__(self):
        return self.user.username

class Follow(models.Model):
    follower = models.ForeignKey(Profile, on_delete=models.CASCADE) 
    following = models.ForeignKey(Profile, on_delete=models.CASCADE)
    followed_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.following} <- {self.follower}'

class NewPost(models.Model):
    username = models.CharField(max_length=64)
    body = models.CharField(max_length=64)
    likes = models.IntegerField(default=0)
    timestamp = models.DateTimeField(auto_now_add=True)

The above Follow model saves the record of the follows.

For example there are two users A and B so if A starts following B then the Follow model will save a record in that follower will be A and following will be B and the followed_on will be the date when the user A started following user B .

You can also write a signal for adding the follower count when a user follows another user.

see below:

from djano.dispatch import receiver
from django.db.models.signals import post_save

@receiver(post_save, sender=Follow)
def add_follow_count(sender, instance, created, **kwargs):
    try:
        if created:
           user = Profile.objects.get(id=instance.following.id)
           user.followers +=1
           user.save()
    except Exception as e:
        print("Error incrementing follower count.")
        print(e)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM