Home > front end >  query ManyToManyfield for requested user
query ManyToManyfield for requested user

Time:03-08

I have two models, a user model and a sport model. These two models have a m2m relationship as a user can do multiple sports and a sport can be played by more than one user. I want to get a query set of a user's sports, so only the sports a specific user does shows up for that user.

I have created a context_processors.py file so that the information is available on all pages of the site. The problem is that I don't know how to query the database to get this information.

These are my models:

class Sport(models.Model):
    name = models.CharField(max_length=100, null=False)
    

class User(AbstractUser):
   ...
   sports = models.ManyToManyField(Sport)

Right now, I get all the sports available, like this

def test(request):
    sports = Sport.objects.all()
    return {
        'x': sports
    }

I just want to get the sports the requested user is assigned to in the sports variable.

CodePudding user response:

There are usually two options here:

Sport.objects.filter(user=request.user)

or:

request.user.sports.all()

both will make the same database query. You should use the @login_required decorator [Django-doc] to prevent non-authenticated users from visiting the view, since then request.user is not a user object. Furthermore a view can not return a dictionary: it should return a HttpResponse object, for example by rendering a template:

from django.contrib.auth.decorators import login_required

@login_required
def test(request):
    context = {
        'sports': request.user.sports.all()
    }
    # …

CodePudding user response:

sports = request.user.sports.all()

CodePudding user response:

If you are looking for the sports played by the user, you have to filter the sports model queryset specific to the User row.

Sports.objects.filter(user__id = request.user.id)

Since Sports and User has manytomany relationship, you can access "User" model attribute in Sports model related queries. "id" is the auto-generated key, if you are using any primary key you can replace "id" with that.

  • Related