与Django建立一对多关系 [英] Create a one to many relationship with Django
问题描述
伙计们,我正在制作一个社交媒体应用程序,我有一个用户表,其中使用了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)
推荐答案
您可以尝试以下方式:
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)
上面的 Follow
模型保存以下记录.
The above Follow
model saves the record of the follows.
例如,有两个用户 A
和 B
,因此,如果 A
开始关注 B
,则关注模型将保存一条记录,其中 follower
将为 A
,并且 following
将为 B
,并且 followed_on
是用户 A
在用户 B
之后开始的日期.
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.
请参见下文
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)
这篇关于与Django建立一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!