Awesome q2a theme

How to make a query in django?

0 like 0 dislike
26 views
For example, there are two models and Message Manager.

class Manager(models.Model): name = models.CharField(max_length=255) create = models.DateTimeField(auto_now_add=True)


class Message(models.Model): text = models.TextField() manager = models.ForeignKey(Manager, models.SET_NULL, null=True)


Need to get the last 5 created Manager and to each of them belonging to the message.
How can I do that in the template to use a single object?
Or it is necessary in the first view to Manager
Managers = Manager.objects.all().order_by('-create')[:5]

And then using a loop to query
Messages = Enc.objects.filter(manager=Managers[i])
B as it is to try to combine in a single object or a list then cycles in the display template.
Is there a simpler way?
by | 26 views

1 Answer

0 like 0 dislike
This is certainly not the case, but it is better still to arrange the code using tags.
Redo the model as follows:
class Message(models.Model): text = models.TextField() manager = models.ForeignKey(Manager, models.SET_NULL, null=True, related_name="messages")

Applying the migration you will be able to access the messages from the model Manager. For example:
somemanager=Manager.objects.first() messages=somemanager.messages

Well, then have it display in the template as you need
by

Related questions

0 like 0 dislike
2 answers
asked May 1, 2019 by tuychiev1988
0 like 0 dislike
1 answer
asked May 12, 2019 by AlexKulaga
0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
110,608 questions
257,187 answers
0 comments
40,796 users