我有以下型号:
class UserProfile(models.Model):
user = models.OneToOneField(User)
class Site(models.Model):
user = models.ForeignKey(User)
site_name = models.CharField(max_length=128, blank=False, null=False)
class Team(models.Model):
site = models.ForeignKey(Site)
team_member_name = models.CharField(default='name', max_length=128, blank=False, null=False)
我有一个通过网址传递team_member
ID的视图:
Urls.py:
url(r'^team/(?P<team_member_id>\d+)/$', 'team.views.home', name='team_view_team_member')
Views.py:
@login_required
def home(request, team_member_id=None):
team_member = Team.objects.get(id=team_member_id)
请注意,有许多Team
个实例(即许多团队成员)具有相同的Site_id
。
如何测试request.user
与site_id
返回的team_member
是否相同?如果我想在多个视图中使用它,是否有一种简单的方法可以重复此操作?
答案 0 :(得分:2)
试试这个:
team_member = Team.objects.get(id=team_member_id)
if team_member.site.id == request.user.site_set.all().first().id:
print "same site"
else:
print "different site"
答案 1 :(得分:1)
希望这有帮助。
# Site for user in request
req_user_site = Site.objects.get(user=request.user) # Use filter if it will return more than one object
# Site for team member in url
sites = Site.objects.filter(team__pk=team_member_id)
# Then compare
if req_user_site in sites:
print "have the same"
else:
print "don't"