简体   繁体   中英

Loop in ManyToMany Fields in django model

I have a model like this:

class MyProfile(models.Model):
      club = models.ManyToManyField(Club, default=None)
      city = models.ManyToManyField(City, default=None)
      .
      .

In view:

user = User.objects.get(pk=id)
profile = MyProfile.objects.select_related().get(user=user)

With for example profile.club.select_related() I can find user's club. But I want do this in loop.

fileds = [car, club]
for f in fileds:
        print getattr(profile, f)

In the output I have <django.db.models.fields.related.ManyRelatedManager object at 0x9876545> But with profile.club.select_related() I can recieve user's club name. I cant use this query in loop. Is there any way to use such query for list of model fields?

Thanks in advance

This fields are the same as "objects" field in MyProfile class. Adding .all() and casting it to list.

fields = [car, club]
for f in fields:
    z = getattr(profile, f)
    print list(z.all())

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