Django-通过字段过滤相关对象

时间:2019-07-23 16:26:51

标签: django django-models django-orm

我有以下型号

class User(models.Model):
    ...
    following = models.ManyToManyField('self', blank=True, through='relationships.Relationship', symmetrical=False, related_name='followers')


class Relationship(models.Model):
    from_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='from_user')
    to_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='to_user')
    status = models.CharField(max_length=255, default=RelationshipStatus.ACCEPTED.value, choices=[(state.value, state.name) for state in RelationshipStatus])


class RelationshipStatus(Enum):
    ACCEPTED = 'accepted'
    PENDING = 'pending'
    REJECTED = 'rejected'

我想获取给定用户的关注者,但只有拥有批准关系的关注者。

使用以下查询很容易。

Relationship.objects.filter(to_user=a_user, status=RelationshipStatus.ACCEPTED.value)

但是我的问题是,如何使用用户的followers属性来做到这一点?

如果我做a_user.followers.all(),我会把所有的都拿走,但我只希望那些关系被接受的人。

那些不起作用

a_user.followers.filter(status=RelationshipStatus.ACCEPTED.value)a_user.followers.filter(relationship__status=RelationshipStatus.ACCEPTED.value)

因为引发了以下异常

django.core.exceptions.FieldError: Cannot resolve keyword 'relationship' into field.
django.core.exceptions.FieldError: Cannot resolve keyword 'status' into field.

1 个答案:

答案 0 :(得分:1)

尝试一下:

a_user.followers.filter(to_user__status=RelationshipStatus.ACCEPTED.value)

因为您已经为字段related_name='to_user'指定了to_user。但是,也许表示“关系”的名称更合适,或者您可能对此感到困惑。