我有以下相关模型:
我希望能够获取给定用户的所有
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.
我希望能够获取给定用户的所有
mutual_contacts
的position
。目前我正在进行以下(低效)操作:>>> 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)能够用来实现相同的功能吗?