D
D
Domohod2021-12-29 16:31:24
Python
Domohod, 2021-12-29 16:31:24

How to retrieve all data from database?

I'm doing a vote in Python Django, the main page should display the result of the votes of all users, but I only display the results of the current user. How to fix it?

views.py

def home(request):
    value, create = Choose.objects.get_or_create(voter=request.user)
    context = {
        "value": value,
    }

    return render(request, 'registration/home.html', context)


def black(request):
    if request.user.is_authenticated:
        value, created = Choose.objects.get_or_create(voter=request.user)

        if request.method == 'POST':
            select_action = request.POST['choose']

            if select_action == 'black':
                value.count_black += 1
                value.save()
            else:
                return render(request, 'registration/black.html', {"value": value})

            return redirect("home")


models.py:
class Choose(models.Model):
    count_black = models.PositiveIntegerField(default=0, verbose_name="black")
    count_white = models.PositiveIntegerField(default=0, verbose_name="white")
    count_purple = models.PositiveIntegerField(default=0, verbose_name="purple")
    voter = models.ForeignKey(User, null=True, blank=True, verbose_name='Пользователь', 
    on_delete=models.PROTECT)


html:
<h1 style="color: white">{{ value.count_black }} </h1>


So, in my admin panel, the results of various users are saved, but only the votes of the current one (the one I entered) are displayed. How to display the entire result?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Nesterov, 2021-12-29
@Domohod

1. Did you read the docs (well, or at least articles) on ORM django?
2. Did you write the code yourself?
Something tells me that in both cases - no, because it is very easy not to understand how this method works, even having minimal knowledge on the topic (and even just knowing English and being friends with logic).
Choose.objects.get_or_create(voter=request.user)
It tries to find a suitable object, and if it doesn't exist, it creates it. That's all

V
Vindicar, 2021-12-29
@Vindicar

value, create = Choose.objects.get_or_create( voter=request.user )

Maybe that's why?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question