QuerySet获取用户联系人的所有属性?

时间:2012-02-28 03:23:35

标签: python django django-models

我有以下相关型号:

class PositionTimestamp(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    position = models.ForeignKey('Position')
    profile = models.ForeignKey('UserProfile')

class Position(models.Model):
    position = models.CharField(max_length=100)
    ordering = models.IntegerField(max_length=3)
    select_display = models.CharField(max_length=100)

class UserProfile(models.Model):   
    def mutual_contacts(self):
        # returns all of the current User's contacts. A QuerySet of UserProfile objects.

我想获得给定用户position的所有mutual_contacts s。这是我目前(效率低下)做的事情:

>>> p = UserProfile.objects.get(id=1)
>>> position_set=[]
>>> for profile in p.mutual_contacts():
        position_set.append(p.positiontimestamp_set.all())
>>> position_set
    [[<PositionTimestamp: PositionTimestamp object>, <PositionTimestamp: 
    PositionTimestamp object>, <PositionTimestamp: PositionTimestamp object>]]
>>> position_set = set([item.position for item in position_set[0]])

>>> position_set
    set([<Position: Director>, <Position: Writer>, <Position: Editor>])

可以使用QuerySet来获得相同的内容吗?

1 个答案:

答案 0 :(得分:0)

要获取给定用户集的所有位置,请尝试以下代码:

p = UserProfile.objects.get(id=1)
contacts = p.mutual_contacts()
positions = Position.objects.filter(positiontimestamp__profile__in=contacts)