Как считать параметр id, выбрать по нему нужно название и по названию вывести записи связаной таблицы:?

Имеется представление со списком всех пользователей, по клику на каждого должен быть переход на отображение кто как проголосовал. Как выбрать из таблицы нужных пользователей и их данные. В нужной таблице все поля FK и создаются методом (create- правильно я поступил? потому что названия пользователей дублируются - выходит множество полей с одним именем(user) и разными полями (question),(statistic). нужно вывести все варианты для каждого user).
#modelS
import datetime
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone

class Question(models.Model):
	question_text = models.CharField(max_length=200)
	pub_date = models.DateTimeField('date published')
	def __str__(self):
		return self.question_text
	def was_published_recently(self):
		now = timezone.now()
		return now - datetime.timedelta(days=1) <= self.pub_date <= now
		was_published_recently.admin_order_field = 'pub_date'
		was_published_recently.boolean = True
		was_published_recently.short_description = 'Published recently?'


class Choice(models.Model):
	question = models.ForeignKey(Question)
	choice_text = models.CharField(max_length=200)
	votes = models.IntegerField(default=0)
	def __str__(self):
		return self.choice_text

class Statistic(models.Model):
	user = models.ForeignKey(User, related_name='statistic_user')
	question = models.ForeignKey(Question)
	vote = models.ForeignKey(Choice)
	def __str__(self):
		return str(self.user)

#вьюха для сохранения в бд и отображения всех юзеров
class ResultsView(generic.DetailView):
	model = Question
	template_name = 'polls/results.html'

def vote(request, question_id):
    p = get_object_or_404(Question, pk=question_id)
    current_user = request.user
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])

    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': p,
            'error_message': "You didn't select a choice.",
        })
    else:
        q = Question.objects.get(id=question_id)
        selected_choice.votes += 1
        selected_choice.save()
        c = Choice.objects.get(question=question_id)
        stat = q.statistic_set.create(user=current_user, question=question_id, vote=c)
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

def results(request, question_id):
	question = get_object_or_404(Question, pk=question_id)
	return render(request, 'polls:results.html', {'question': question})

class ListView(generic.ListView):
    model = User
    template_name = 'polls/list.html'
    context_object_name = 'user_list'

    def get_queryset(self):
        return User.objects.all().order_by('-username')[:5]

#urls
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
    url(r'list/$', views.ListView.as_view(), name='list'),
    url(r'^(?P<pk>[0-9]+)/statistic/$', views.StatisticView.as_view(), name='statistic'),
   	#url(r'(?P<user_id>[0-9]+)/statistic/$', views.statistic, name='statistic'),
]

#представление "list.html" с которого переходим
{% for user in user_list %}
			<li><a href="{% url 'polls:statistic' user.id %}">{{ user.username }}</a></li>
		{% endfor %}
  • Вопрос задан
  • 254 просмотра
Решения вопроса 1
koshalex
@koshalex Автор вопроса
p.s.[1] - у меня через фильтр по связи не выходит. типа User.statistic_user.filter
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы