Reputation: 535
I have on my projects two apps: account_app and image_app which have the models below.
I am wondering if it is possible to directly access the number of likes of one profile, which has a OneToOne relation with User(django bultin) that in turn has a ManyToMany relation with Images user_like.
account_app/models.py
class Profile(models.Model):
# quando usar a relacao nao colocar o nome User de vez, tem que usar dessa forma
# essa relacao nos permite linkar o perfil com o usuario
user = models.OneToOneField(settings.AUTH_USER_MODEL)
date_of_birth = models.DateField(blank=True, null=True)
photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True)
image_app/models.py
class Image(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created')
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, blank=True)
url = models.URLField()
image = models.ImageField(upload_to='images/%Y/%m/%d')
description = models.TextField(blank=True)
created = models.DateField(auto_now_add=True, db_index=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked',blank=True)
Upvotes: 0
Views: 167
Reputation: 42
You can also introduce a property likes
in Profile Model.
class Profile(models.Model):
# quando usar a relacao nao colocar o nome User de vez, tem que usar dessa forma
# essa relacao nos permite linkar o perfil com o usuario
user = models.OneToOneField(settings.AUTH_USER_MODEL)
date_of_birth = models.DateField(blank=True, null=True)
photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True)
@property
def likes(self):
self.user.images_liked.count()
Upvotes: 1
Reputation: 78556
Given a Profile instance profile
, you may get the number of users_like
with:
number_of_likes = profile.user.images_liked.count()
Upvotes: 0