2017-04-21 85 views
0

pp.pprint(AppUser.objects.filter(directory__user_id = F( '身份證'))查詢。STR())Django的ORM連接查詢問題

('SELECT "users_appuser"."id", "users_appuser"."password", ' 
'"users_appuser"."last_login", "users_appuser"."is_superuser", ' 
'"users_appuser"."username", "users_appuser"."first_name", ' 
'"users_appuser"."last_name", "users_appuser"."email", ' 
'"users_appuser"."is_staff", "users_appuser"."is_active", ' 
'"users_appuser"."date_joined", "users_appuser"."gender", ' 
'"users_appuser"."age", "users_appuser"."avatar", "users_appuser"."about", ' 
'"users_appuser"."city", "users_appuser"."state", ' 
'"users_appuser"."location", "users_appuser"."location_updated", ' 
'"users_appuser"."online", "users_appuser"."entered_offline", ' 
'"users_appuser"."notifications", "users_appuser"."checkins", ' 
'"users_appuser"."lock_expiration" FROM "users_appuser" INNER JOIN ' 
'"chat_membershiphistory" ON ("users_appuser"."id" = ' 
'"chat_membershiphistory"."user_id") WHERE ' 
'"chat_membershiphistory"."user_id" = ("users_appuser"."id")') 

我需要包括從所有價值chat_membership到最終的查詢

這是我的模型類

class MembershipHistory(TimeStampedModel): 
    Active = "A" 
    Offline = "O" 
    Away = "X" 
    NEVER_JOINED = "N" 
    Locked = "L" 

    _STATUSES = ((Active, 'Active'), (Offline, 'Offline'), (Away, 'Away'), 
       (Locked, 'Locked'), 
       (NEVER_JOINED, 'Never joined')) 

    room = models.ForeignKey('places.Place', related_name='directory') 
    user = models.ForeignKey(AppUser, related_name='directory') 
    lock_expiration = models.DateTimeField(null=True, 
              blank=True, 
              editable=True) 
    type = models.CharField(max_length=1, 
          blank=False, 
          null=False, 
          choices=_STATUSES, 
          default="A") 

    class Meta: 
     ordering = ('room', 'user') 
     unique_together = ('room', 'user') 
     verbose_name = "Member" 
     verbose_name_plural = "Members" 

如果我嘗試select_related我總是得到以下兒ROR

Invalid field name(s) given in select_related: 'directory'. Choices are: auth_token 

回答

0

您應該使用prefetch_related

prefetch_related('directory') 
+0

不工作,以及 - https://gist.github.com/dmitry-saritasa/5934312039c5537d9052db8f8da1a8ec – DmitrySemenov