SQL statement into view

I’m doing my first steps in django and I’m trying to translate this sql into a view.

this is the 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):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)```

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

this is the sql:
```select DISTINCT question_text from polls_choice c, polls_question q
where c.question_id = q.id```

this is what i've got in the view:
```def index(request):
    latest_question_list = Question.objects.all().distinct(Question).order_by('-pub_date')
    context = {'latest_question_list': latest_question_list,}
    return render(request, 'polls/index.html', context)```

I'm getting this error:
```# AttributeError at /polls/

type object 'Question' has no attribute 'split'

|Request Method:|GET|
| --- | --- |
|Request URL:||
|Django Version:|4.1.3|
|Exception Type:|AttributeError|
|Exception Value:|type object 'Question' has no attribute 'split'|
|Exception Location:|/Users/demiguelfreitas/develop-env/lib/python3.8/site-packages/django/db/models/sql/compiler.py, line 863, in get_distinct|
|Raised during:|polls.views.index|
|Python Executable:|/Users/demiguelfreitas/develop-env/bin/python3|
|Python Version:|3.8.1|
|Python Path:|['/Users/demiguelfreitas/develop-env/luproject', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Users/demiguelfreitas/develop-env/lib/python3.8/site-packages']|
|Server time:|Tue, 22 Nov 2022 18:00:47 +0000|```

this is the index.html template:
```{% if latest_question_list %}
    {% for question in latest_question_list %}
        <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}
{% else %}
    <p>No polls are available</p>
{% endif %}```

can someone help on this?
Thanks in advance

When posting code, templates, or error messages here, please surround each file (or template, etc) between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code (or template, or error, etc), then another line of ```.
This forces the forum software to keep your code properly formatted, which is critical with Python.

You can edit your original post to add those lines of ``` before and after each set of contents.

See the docs and examples for how to use distinct.

Side note - you’re close with the backticks, but they do need to be on lines by themselves.

Thank you @KenWhitesell for the explanation, but you did not reply to my question. I’ve seen the documentation already but I can’t figure out the solution, that’s why I posted the question here, to find help.
I’m new to this and I appreciate some help.
thanks again.

Ok, what parameters does the example show as being passed to the distinct function?

What are you passing as the parameter to that function?

I’m passing question as a parameter

You’re passing Question as a parameter. Question is a class, specifically a Model.

If you look at one of the examples from the docs:

you can see that the proper parameter to pass in to distinct is a string, representing a field name.

The error you’re getting is caused by you passing the wrong data type as a parameter into the distinct function.

That’s how the views.py look like now:

def index(request):
    **latest_question_list = Question.objects.order_by('question_text').distinct('question_text')**
    context = {'latest_question_list': latest_question_list,}
    return render(request, 'polls/index.html', context)

On the browser I get this error message:

Error during template rendering
In template /Users/demiguelfreitas/develop-env/luproject/polls/templates/polls/index.html, error at line 1

DISTINCT ON fields is not supported by this database backend

This is the index.html

{% if latest_question_list %}
    {% for question in latest_question_list %}
        <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}
{% else %}
    <p>No polls are available</p>
{% endif %}

What do you think this error is telling you?

What information on that referenced docs page might be relevant?

SQLite, the DB that I’m using, does not support distinct ON fields.

1 Like