Reputation: 305
I am developing web app for tracking orders. And I would like to display all orders which were created by a user via detailView.
models.py
class Order(models.Model):
...
user = models.ForeignKey(MyUser, on_delete=models.CASCADE)
order_number = models.CharField(max_length=150)
class MyUser(models.Model):
eid = models.CharField(max_length=7)
name = models.CharField(max_length=150)
surname = models.CharField(max_length=150)
views.py
class UserDetailView(generic.DetailView):
model = MyUser
template_name = "database/user_detail.html"
def get_queryset(self):
return Order.objects.all().order_by("-id")
user_detail.html
{% extends "base.html" %}
{% block content %}
<body>
<h1> {{ user.eid }} {{ user.name }} {{ user.surname }}
</h1>
{% for order in orders %}
order.order_number
{% endfor %}
{% endblock %}
With this code I receive error: page not found: No Order found matching the query.
If i delete the def get_queryset()
in the views.py, it shows only the users eid and name. Not sure how I can get all the assigned orders to the particular user.
Upvotes: 0
Views: 3175
Reputation: 723
Django allows you to follow relationships "backwards", meaning you can query all records of a modelB that has a FK or OneToOne relationship to your modelA.
class ModelA(models.Model):
pass
class ModelB(models.Model):
model_a = models.ForeignKey(ModelA)
...
modela = ModelA.objects.get(id=x)
queryset = modela.modelb_set()
That said, you can do this in your template:
{% for order in user.order_set.all %}... {% endfor %}
More info here: https://docs.djangoproject.com/en/2.2/topics/db/queries/#following-relationships-backward
Upvotes: 1
Reputation: 1024
There are two issues with your code. The first one was mentioned by Higor Rossato in the comments, if you want to list mutiple things you should use a generics.ListView
. You shoudl also change the model
and get_queryset
attributes of your view.
You want model=Order
and
def get_queryset(self):
Order.objects.filter(user=self.request.user).order_by("-id")
then you should add a get_context_data method to pass your user's information.
Upvotes: 1
Reputation: 1592
In the template try:
{% for order in user.order_set.all %}
<p>{{ order.order_number }}</p>
{% endfor %}
This uses the foreign key relation to get the orders for a given MyUser
instance.
The get_queryset()
method is used to return a queryset in which to look for the object for the detail view.
Upvotes: 2