What does join do in django's views.py?

Asked 2 years ago, Updated 2 years ago, 81 views

Sorry for the amateur question, but

in the code below
output=','.join([q.question_text for qin latest_question_list])

I don't know what the part is doing.I thought question_text separated by
This was the first time I encountered a join that was followed by a for statement, and I couldn't understand it well when I googled it.If question_text is included for each element of latest_question_list (=question_text?), question_text is confusing for both question_text and for question_list

Could someone tell me the meaning of this code?

polls/views.py

 from django.http import HttpResponse

from.models import Question

# q.question_text has only one object: <Question: What's new?>

def index(request):
    latest_question_list =Question.objects.order_by('-pub_date') [:5]
    output=','.join([q.question_text for qin latest_question_list])
    return HttpResponse (output)

# Leave the rest of the views (detail, results, voice) unchanged

models.py

import datetime

from django.db import models
from django.utils import timezone

# Create your models here.
class Question (models.Model):
    question_text=models.CharField(max_length=200)
    pub_date=models.DateTimeField('date published2')
    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

python sql django

2022-09-30 14:29

1 Answers

Concatenating the latest questions with ",".

>>q_list=['aa', 'bb', 'cc']
>>> output=', '.join ([q for q in q_list])
>> output
'aa, bb, cc'

Supplementary

I encountered a join followed by a for statement for the first time, and I couldn't understand it well when I googled it.

If you read this page, you'll find out.

https://note.nkmk.me/python-list-comprehension/


2022-09-30 14:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.