S
S
Sergey Kirikov2018-05-03 07:26:19
Django
Sergey Kirikov, 2018-05-03 07:26:19

How to make a request in django?

For example, there are two models Manager and Message.

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)

You need to display the last 5 Managers created and each of them's messages.
How can it be done that in the template to use one object?
Or you must first get the Manager in the view
Managers = Manager.objects.all().order_by('-create')[:5]

And then, using the cycle, make a request
Messages = Enc.objects.filter(manager=Managers[i])
B somehow try to combine it into one object or list, so that later it can be output into a template in cycles.
Is there an easier way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita, 2018-05-03
@vasilek-nik

This is of course not the case, but it's better to format the code using tags.
Modify the message model like this:

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

By applying the migration, you will be able to access messages from the manager model. For example like this:
somemanager=Manager.objects.first()
messages=somemanager.messages

Well, then output this already in the template as you need

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question