Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django: Filtering items in generic.ListView

I’m creating a game website and i have these models for games:

class Game(models.Model):
    accountant = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='games')

    title = models.CharField(max_length=50)

    bank_money = models.IntegerField()
    player_starting_money = models.IntegerField()
    golden_card_amount = models.PositiveIntegerField(
        validators=[
            MinValueValidator(100),
            MaxValueValidator(1000)
        ]
    )

now i want every user to see their own games at dashbard:

class DashboardView(mixins.LoginRequiredMixin, generic.ListView):
    template_name = 'games/dashboard.html'
    model = models.Game

how can i do this (show every user their own games, not all games)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can override the get_queryset method for your DashboardView class to filter out only logged in user games.

class DashboardView(mixins.LoginRequiredMixin, generic.ListView):
    template_name = 'games/dashboard.html'
    model = models.Game

    def get_queryset(self):
        queryset = super().get_queryset().filter(accountant=self.request.user)
        return queryset
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading