Django ORM, accessing the attributes of relationships
<p>I have on my projects two apps: account_app and image_app which have the models below.</p>

<p>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.</p>

<p><strong><em>account_app/models.py</em></strong></p>

<pre><code>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)
</code></pre>

<p><strong><em>image_app/models.py</em></strong></p>

<pre><code>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)
</code></pre>

<p>You can also introduce a property <code>likes</code> in Profile Model. </p>

<pre><code>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()
</code></pre>

python django django-models