简体   繁体   中英

Get '_set' for a many-to-many relationship with a through

I've got a user model like this:

class Person(AbstractUser):
    id = models.AutoField(primary_key=True)
    ...(additional attributes taken out for brevity)...
    kids = models.ManyToManyField(
        'Person', through='Relationship', related_name='parents')

and a Relationship model that looks like this:

class Relationship(models.Model):
    parent_id = models.IntegerField()
    kid_id = models.IntegerField()

    class Meta:
        unique_together = ('parent_id', 'kid_id')

I'm trying to figure out the best way to get a set of the kids related to a particular parent (who would be the ones logged in).

I've got something like this:

user = Person.objects.get(id=request.user.id)
print(user.relationship_set.all())

But that gives me an error 'Person' object has no attribute 'relationship_set'

How best would I accomplish this?

我最终选择了一条稍微不同的路线并使用了此过滤器:

Person.objects.filter(id__in=[ r.kid_id for r in Relationship.objects.filter( parent_id=person_id ) ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM