0

I am running a query and want to display all fields.

question = Question.objects.get(pk=question_id)

In a model

class Question(models.Model):
    #id = models.AutoField(primary_key=True)
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text

When I print data in a view it returns me only question text, I also want to display id and date.

template

{{ question }}
Harman
  • 1,703
  • 5
  • 22
  • 40

3 Answers3

3

You will have to specify the attribute in your template, like {{ question.question_text }}. Just using {{ question }} works because the repr, which defaults to str is defined as the question_text attribute.

shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
1
question = Question.objects.filter(pk=question_id)

template

{% for x in question %}
    {{x.pub_date}}
{% endfor %}

or your way template {{question.pub_date}}

Marin
  • 1,098
  • 14
  • 33
0

Instead of __str__ you should use __unicode__. See: Python __str__ versus __unicode__

Also, you should access in the template each field separately, but if you want to get just string with id, text and date, you can modify the method, so it returns all as a single string like:

def __unicode__(self): return unicode(self.id)+", "+self.question_text+", "+unicode(self.pub_date)

Community
  • 1
  • 1