Reputation: 1658
I am studying Django and SQL and I have proposed to create a social network in which I can add all the reactions of a publication and add it to a new field where they are all added.
from django.db import models
# Create your models here.
class Post(models.Model):
# User
user = models.OneToOneField(User, on_delete=models.CASCADE)
post = models.TextField(max_length=500000)
# Data
comments = models.IntegerField()
reactions = models.IntegerField()
## Reaction Data
like = models.IntegerField()
love = models.IntegerField()
wow = models.IntegerField()
sad = models.IntegerField()
angry = models.IntegerField()
That is the model of publications, there is a field called reactions, and that will be the sum of all the reactions that publication has acquired. How can I create that sum?
Upvotes: 0
Views: 31
Reputation: 179
Such architecture will be a little wrong.
from project_name import settings
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=50)
text = models.TextField()
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='post_likes')
love = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='post_loves')
# ... another reactions
created_date = models.DateTimeField(default=timezone.now)
settings.AUTH_USER_MODEL is your User
After that you will then be able to not only know the number of reactions, but also to identify users
To count users:
post = Post.objects.create(author=..., ...) # create post
queryset = post.likes # will return users id, who liked post
queryset.count() # will return number of users
Upvotes: 1