开发者

filter on a many_to_many field

开发者 https://www.devze.com 2023-01-10 15:03 出处:网络
new to django, this might be a simple/obvious question, so I apologise in advance. I have the following model

new to django, this might be a simple/obvious question, so I apologise in advance.

I have the following model

class开发者_运维百科 Team(models.Model):
    name = models.CharField(max_length=100)
    members = models.ManyToManyField(User, related_name="members", blank=True, null=True)

And the following view (controller)

def my_teams(request):
    my_list = Team.objects.filter(???????).order_by('name')
    return render_to_response('teams/index.html', {'my_list': my_list})

The objective of this view is to list only those project which the current logged in user is a member of. Being a many to many relationship there can be many members in each team.

Any advice on how to achieve this would be greatly appreciated.


You didn't describe the Project model but I guess it has a foreign to the Team one. So here is how I would to that :

Project.objects.filter(team__user=request.user).order_by('name')


Slight variation on the answer above as I made a slight mistake copying my code across

my_list = Team.objects.filter(members=request.user).order_by('name')

Thanks for your help!

0

精彩评论

暂无评论...
验证码 换一张
取 消