Django ORM,访问关系的属性

时间:2016-10-13 12:28:02

标签: python django django-models

我的项目中有两个应用:account_app和image_app,其中包含以下模型。

我想知道是否有可能直接访问一个配置文件的喜欢数量,这个配置文件与User(django bultin)有一个OneToOne关系,而这个关系又与Images user_like有一个ManyToMany关系。

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)

2 个答案:

答案 0 :(得分:1)

您还可以在Profile Model中引入属性likes

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()

答案 1 :(得分:0)

鉴于个人资料实例profile,您可以获得users_like的数量:

number_of_likes = profile.user.images_liked.count()