Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding to model with OneToMany and updating existing entries.
I have a couple of Django model questions. I am running the following code as a Django manage extension, which I am new to. 1) I am not certain my "Location.objects.get(city=key)" is correct for OneToMany in my add_server_to_db function. I suspect this is incorrect? 2) How can I harden this so if this is executed twice, it will update existing Server entries vs. error out? Django Server Model: class Servers(models.Model): name = models.CharField(('name'), max_length=128) location = models.OneToOneField('locations.Location', on_delete=models.CASCADE) ip_address = models.CharField(('ip_address'), max_length=128) date = models.DateField(auto_now=True) Django Location Model: class Location(models.Model): city = models.CharField(('city'), max_length=10) geolocation = models.PointField(('location')) Function: def add_server_to_db(data_dict): print(data_dict) for key, val in data_dict.items(): loc = Location.objects.get(city=key) m = Server( location=loc, name=val['name'], ip_address=val['ip_address'], m.save() Thanks. -
Django - How to fix unique constraint fields
I'm making a hobby project and I've got the following model: from django.contrib.auth.models import User from django.db import models class Group(models.Model): name = models.CharField(blank=False, max_length=25) description = models.CharField(max_length=50, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False) def __str__(self): return self.name class Meta: ordering = ('name', ) # my intention is that one user cannot have more than one group with the same name unique_together = ('name', 'user') I would like to make it possible for the user to create new groups by using this generic class based view. from django.urls import reverse_lazy from django.views import generic from groups.models import Group class GroupCreate(generic.CreateView): model = Group fields = [ 'name', 'description' ] success_url = reverse_lazy('ideas:list') template_name = 'groups/group_create.html' def form_valid(self, form): form.instance.user = self.request.user return super(GroupCreate, self).form_valid(form) As long as I don't try to make an error by sending an existing group's name, everything works fine. But if I send an existing group's name (same user!), I get the following error: IntegrityError at /groups/create UNIQUE constraint failed: groups_group.name, groups_group.user_id Why does it occur? How could I fix it or catch the error? I'm using Django 2.0.2 -
How do you execute a join on a foreign key in a nested for loops in Django?
I have two model classes, Part and Chapter shown below class Part(models.Model): title = models.CharField(max_length=200) # part_image = models.ImageField(upload_to=upload_location, # null=True, # blank=True, # width_field="width_field", # height_field="height_field", # verbose_name='Image',) summary = models.TextField() def __str__(self): return self.title class Chapter(models.Model): part = models.ForeignKey(Part, default=None, related_name='part', on_delete=models.CASCADE,) title = models.CharField(max_length=200) hw_link = models.CharField(max_length=200) data_link = models.CharField(max_length=200) code_link = models.CharField(max_length=200) def __str__(self): return self.title The idea is to have each part be its own section that contains the relevant chapters and links. I figured that I could do something similar to this but it isn't returning any of the chapters: {% if part_list %} {% for part in part_list %} <div class="panel panel-default"> <div class="panel-heading"><h1>{{ part.title }}</h1> <h3><small>{{ part.summary }}</small></h3> </div> <div class="panel-body"> {% for chapter in chapter_list %} {% if chapter.part == part.title %} <h3>{{ chapter.title}}</h3> <a href="{{ chapter.hw_link }}"><i class="fa fa-home" aria-hidden="true"><i class="fa fa-briefcase" aria-hidden="true"></i></i> - homework</a>&emsp;&emsp; <a href="{{ chapter.data_link }}"><i class="fa fa-shower" aria-hidden="true"></i><i class="fa fa-table" aria-hidden="true"></i> - clean data</a>&emsp;&emsp; <a href="{{ chapter.code_link }}"><i class="fa fa-free-code-camp" aria-hidden="true"></i><i class="fa fa-file-code-o" aria-hidden="true"></i> - hot code</a> {% endif%} {% endfor %} </div> </div> {% endfor %} {% else %} <p>Part is not working</p> {% endif %} -
custom user model and many to many permissions authentication and authorization django
I have a custom user model that I am building in Django. I'm pretty clear on how its going to work. I though have an interesting permisions scheme. I am trying to confrim if my thought process is correct. Each user can be part of many venues. Of each venue a user is a part of they may have a different permission. I have my user table and then I have a permissions table the permissions table is of the following: pk venueID UserID isclient isvenueviewer isvenueeventplanner isvenueadmin issuitsviewer issuitssuperuser the venue id can be null meaning that no all users will have venues attached to them. my thought is that a user first gets authenticated by the user table then that user object is checked by the permissions table for what permissions that user has. Of those permissions the one needed for the current view to be authorized is filtered through. And see if valid. am I spot on? Thank you hugs and kisses! -
Creating a checkbox in such way that a user gets updated
I am trying to create a way that a student can enroll to a teacher's course. I added a boolean field to my StudentData model and from there I added a many-to-many field to my Course model. Each of my course page is a generated slug page and there all students are listed. I want that near each student a checkbox will be shown. And if teacher selects more students and presses Enroll button, only those students can view the course. Now, the template conditionals I can do them myself, but I am stuck on updating data the right way using the checkbox. This is the boilerplate: class StudentDataForm(forms.ModelForm): enrolled = forms.BooleanField() def __init__(self): if self.checked: self.fields['enrolled'].initial = True class Meta: model = StudentData fields = ('enrolled', ) class StudentData(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=50) student_ID = models.CharField(unique=True, max_length=14) notes = models.CharField(max_length=255, default=None, blank=True) enrolled = models.BooleanField(default=False) course = models.ManyToManyField('Course', default=None, blank=True) class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='') name = models.CharField(max_length=50, unique=True) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) teacher1 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, verbose_name="Course Teacher", related_name='%(class)s_course_teacher') teacher2 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, null=True, verbose_name="Seminar Teacher", related_name='%(class)s_seminar_teacher') slug = … -
how to get node children and print them MPTT
I am pretty new to django and MPTT, I have categories and products in a tree it looks something like this: Category Product1 Category1 Product2 Category21 Category2 Product3 I want to print this tree like this, but I can only print categories, Here is my code: models: class Category(MPTTModel): name = models.CharField(max_length=50, blank=False, unique=True) is_active = models.BooleanField(default=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', db_index=True) class Meta: verbose_name_plural="Categories" def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=50, blank=False, unique=True) price = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=4) is_active = models.BooleanField(default=True) category = TreeForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True, db_index=True) def __str__(self): return self.name my views.py def index(request): categories = Category.objects.get(pk=1).get_descendants(include_self=True) return render(request, 'menu/index.html', {"categories": categories}) my index.html {% load mptt_tags %} <ul> {% recursetree categories %} <li> {{ node.name }} {{ node.set_product }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> My question would be how could I print the same tree, categories with products, Products are leaves. -
JavaScript can't access variables from Django view via HTML
The error I see in my browser console says that 2 variables in my .js throw a Reference Error because they are undefined. This code used to work but now fails as such. I have some code which somehow used to work but now fails. Since replication is very impractical, I'd like to describe the problem and learn how to better troubleshoot it. I can print the data for those variables in the context_dict from views.py and see that the data is there and everything looks OK. Those variables are called module_progressjs and studtests. I can also print the data for those variables within the HTML and see it that way. Why is JavaScript not seeing them? The HTML code to make the context_dict variables available to JS appears valid: <script type="text/javascript"> var studtests = {{ studtests | safe }}; var studobjs = {{ studobjs | safe }}; var integrityjs = {{ integrityjs | safe }}; var studsumryjs = {{ studsumryjs | safe }}; var module_progressjs = {{ module_progressjs | safe }}; var modavg = {{ modavg | safe }}; var tiiavg = {{ tiiavg | safe }}; var tii_progressjs = {{tii_progressjs | safe}}; </script> Everything else appears to be … -
Accessing propertis of OneToOneFiled in the Same model
In the below example I'm trying to make default amount on the receipt the total method of related model bill. Django throws an error. Is there a way to do this? class Bill(models.Model): amount1 = models.DecimalField(max_digits = 11, decimal_places = 2, default=0) amount2 = models.DecimalField(max_digits = 11, decimal_places = 2, default=0) def total_amount(self): return (self.amount1+self.amount2) class Receipt(models.Model): bill = models.OneToOneField(Bill, on_delete=models.CASCADE) amount = models.DecimalField(max_digits = 11, decimal_places = 2, default=bill.total) -
Create separate scoreboard for each league in django
I'm creating a sports betting app as my first django project. My models are: class Bet(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) home_goals = models.IntegerField() away_goals = models.IntegerField() score = models.IntegerField(default=None, null=True) class League(models.Model): id = models.AutoField(primary_key=True, auto_created=True) name = models.CharField(max_length=50) code = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) admin = models.ForeignKey(User, on_delete=models.CASCADE) class UsersToLeagues(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) league = models.ForeignKey(League, on_delete=models.CASCADE) class Meta: unique_together = ('user', 'league') Each user can join multiple leagues. Now I would like to get separate leaderboards for each league. It should contain a list of users assigned to that league and sum of their scores. I was able to do get all data I need but in a very retarded way presented below: def league_standings(request, league_id): league = League.objects.get(pk=league_id) league_members = UsersToLeagues.objects.filter(league_id=league_id) league_members_users = User.objects.filter(id__in=[user.user_id for user in league_members]) ids = [] userbets = [] userscores = [] for player in league_members_users: ids.append(player.id) userbet = Bet.objects.filter(user_id=player.id) userbets.append(userbet) userscore = userbet.aggregate(Sum('score')) userscores.append(userscore) Please advice how to do it smart and properly. Thanks in advance! -
Django run thread/task with database access allways paralell to webserver
I want to build a Mqtt Client, which stores some data in my django database. This client should always run, when the webserver is running. What is the best way to run a thread with database access (django models) paralle to the webserver? If read about the django background task model, but I am not sure if its a good way. -
Not seeing expected database/user in Docker postgres:*
I am dockerizing an existing Django application, but am struggling with initializing a database and connecting. My db service starts up with the following config, which looks right to me: db: build: context: /Users/ben/Projects/project-falcon/project-falcon-containers dockerfile: Dockerfile-db-local environment: POSTGRES_DB: falcon_db POSTGRES_PASSWORD: falcon POSTGRES_USER: falcon ports: - 5432:5432/tcp restart: always At this point, I would expect the separate api container to be able to connect but instead I get django.db.utils.OperationalError: FATAL: role "advocate" does not exist the relevant settings file: from .dev import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASS'], 'HOST': os.environ['DB_SERVICE'], 'PORT': os.environ['DB_PORT'] } } which is built in api and configured thus api: build: context: /Users/ben/Projects/falcon/falcon-backend dockerfile: Dockerfile depends_on: - db - redis environment: DB_NAME: falcon_db DB_PASS: falcon DB_PORT: '5432' DB_SERVICE: db DB_USER: falcon ports: - 8001:8001/tcp volumes: - /Users/ben/Projects/falcon/falcon-backend:/falcon:rw So based on the documentation for the postgres container I expected the POSTGRES_* variables to create the user/database Django expects to connect as/to. But the error message sure makes me think it did not. So based on the docs and the following question: How to create User/Database in script for Docker Postgres I tried the older method of specifying a specific .sql file … -
TimeField displayed as date
Im using Django framework to build a simple inventory management system. There is data in the database populated using the django admin. Now when i display the data on the website (front-end), there is a time field which is displaying the date, although i am beginning to learn django, I assume my models are wrong. Below i've attached my models.py and also the error on the actual site. Models.py # -*- coding: utf-8 -*- from future import unicode_literals import time from django.db import models class Cart(models.Model): def str(self): return self.CartColor CartColor = models.CharField(max_length=255) Quantity = models.CharField(max_length=5) class Initials(models.Model): def unicode(self): return self.Staff Staff = models.CharField(max_length=255) FirstName = models.CharField(max_length=255) LastName = models.CharField(max_length=255) class RTInfo(models.Model): def str(self): return str(self.TicketNo) TicketNo = models.CharField(max_length=10) # TickStamp = models.DateField(auto_now_add=True, blank=True) class Room(models.Model): def unicode(self): return self.Number Number = models.CharField(max_length=5) class TCCheckOut(models.Model): def str(self): return str(self.ReturnDate) ReturnDate = models.DateField(auto_now_add=True, blank=True) ReturnTime = models.TimeField(auto_now_add=True, blank=True, unique_for_date=True) OutQuantity = models.CharField(max_length=255) Staff = models.ForeignKey(Initials, on_delete=models.CASCADE) Number = models.ForeignKey(Room, on_delete=models.CASCADE) CartColor = models.ForeignKey(Cart, on_delete=models.CASCADE) TicketNo = models.ForeignKey(RTInfo, related_name="custom_user1_profile", on_delete=models.CASCADE) # TickStamp = models.ForeignKey(RTInfo,related_name="custom_pass2_profile", on_delete=models.CASCADE) class TCCheckIn(models.Model): def str(self): return str(self.Date) Date = models.DateField(auto_now_add=True, blank=True) Time = models.TimeField(auto_now_add=True, blank=True) Quantity = models.CharField(max_length=255) Staff = models.ForeignKey(Initials, on_delete=models.CASCADE) Number = models.ForeignKey(Room, on_delete=models.CASCADE) CartColor … -
Django won't connect to Redis Docker container
I've spent forever trying to connect my Django container to Redis while using Docker-Compose. After hours of changing Docker and Django configs and trying different ways to run everything, I finally figured out that Redis was broadcasting to the host. These were the errors I was getting each try: Error 111 connecting to 0.0.0.0:6379. Connection refused. Error 61 connecting to localhost:6379. Connection refused. Error 111 connecting to 127.0.0.1:6379. Connection refused. -
Auto Generated Admin Dashboard For Meteor.js
I was interested if the is a package which auto generates an admin dashboard for a meteor application. Something similar to the admin dashboard of django. It seems that there are two popular solutions: - https://github.com/yogiben/meteor-admin - https://github.com/gterrono/houston/ The first has a problematic package dependency, which changing it causes my app to break, and the second one is no longer maintained and also causes artifacts in the app. I am wondering if there is some other package, which I might have missed? If not, which alternative is recommended to manage users, and the app's collections? Thanks and best regards -
Serialize OneToMany relation into array in Django
Suppose I have some django models: class Restaurant(Model): name = CharField(max_length=200) class Food(Model): restaurant = ForeignKey(Restaurant, on_delete=CASCADE) name = CharField(max_length=200) One Restaurant can have multiple foods. And I want my json to look like this: [ { "name": "xxx", "food": [{"name": "xxx"}, {"name": "xxx"}, ...] }, ... ] I can use something like: restaurants = Restaurant.objects.all().values() for restaurant in restaurants: restaurant['food'] = Food.objects.filter(restaurant__id=restaurant['id']).values() But this loses some optimization in SQL level, as this is using application level loop. Is there a better way to do this? -
Need advice on implementing feature regarding Django models
I need some kinds of advice. In my models I have teachers, students and courses. Each teacher has its own courses. I was wondering how can I allow students to visualize my courses, as a teacher. In the teacher classroom (teacher control panel), I listed his courses, and near each course I made an enroll students button. So when that is clicked on, it will redirect to the course's slug page and there he will be able to search for his students (like classroom/engineering/enroll). This is what I done so far. Now I was thinking of some kind of boolean value checkbox near each student name and when all desired students are checked, below he will have an Enroll button, which will allow those students to visualize that course page. My problem is, how do I implement this enroll exactly ? What is a good approach ? Please advice me. -
Performance problems while creating multiple objects
My aim is to create a matrix with individual editable fields. Since different people should only be allowed to edit certain fields I thought about creating an object called CellCE and an object level permission. my models.py class CellCE(models.Model): row = models.ForeignKey('Descriptor',related_name='activecell', on_delete=models.CASCADE) col = models.ForeignKey('Descriptor',related_name='passivecell', on_delete=models.CASCADE) val = models.IntegerField(default=0) project = models.ForeignKey('Project', on_delete=models.CASCADE, default='1') #permission for Cells class Meta: permissions = ( ("edit_cellCE", "Has permission to edit value of Cause and Effect cell"), ) @classmethod def create(cls, row, col, project): CellCE = cls(row=row, col=col, project=project) CellCE.save() return CellCE my views.py def phase2(request, id): projectname = get_object_or_404(Project, pk=id) projectid = id project = Project.objects.get (id=projectid) projectdescriptors = Descriptor.objects.filter( project=projectid) for Descriptor.id in projectdescriptors: row = Descriptor.id for Descriptor.id in projectdescriptors: col = Descriptor.id if CellCE.objects.filter(row=row, col=col, project=project).exists(): pass else: obj = CellCE.create(row, col, project) CellCElist = CellCE.objects.filter(project= project) context = {'CellCElist': CellCElist, 'projectname': projectname, 'projectid': projectid, 'projectdescriptors': projectdescriptors} return render(request, 'szenario/phase2.html', context) my template <table> {% for drow in projectdescriptors %} {% if forloop.first %} <tr> <th align="left">Descriptors</th> {% for value in projectdescriptors %} <th>{{value}}</th> {% endfor %} </tr> {% endif %} <tr> <th align="left">{{drow}}</th> {% for dcol in projectdescriptors %} <td align="center"> {% if forloop.parentloop.counter == forloop.counter %} - … -
django query datetime filed issue
i have tried to apply filter datetime filed in django query,but i got result zero the below code i have tried: Customers.objects.filter(created_at__month=1).count() but select id,created_at from customer_customers; +----+----------------------------+ | id | created_at | +----+----------------------------+ | 1 | 2017-12-24 06:54:41.264756 | | 2 | 2017-12-24 07:05:37.317395 | | 3 | 2017-12-24 10:05:29.957158 | | 4 | 2017-12-29 13:30:21.572926 | | 5 | 2017-12-29 13:58:59.137774 | | 6 | 2017-12-31 08:46:13.239080 | | 7 | 2017-12-31 09:04:34.695830 | | 8 | 2017-12-31 12:27:05.253016 | | 9 | 2018-01-27 12:28:16.809840 | | 10 | 2018-02-14 07:27:18.847884 | | 11 | 2018-02-14 10:45:33.323448 Expected result should be 2 -
cURL doesn't show JSON data when using Django REST Framework
I'm having a problem with the tutorial for the Django REST framework 2. I'm using cURL to test the serializer I've built. I've also added some snippet data to the database. According to the tutorial, I should be able to do this: curl http://127.0.0.1:8000/snippets/ and see this: [{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}] I would also expect to see an HTTP response code of 200 where the Django server is running. If I simply enter the URI in my browser, I see the JSON data in my browser and the 200 response code in the Django server console. But when I run the curl command from the terminal command line, I don't see anything and I get a 301 HTTP response code in the Django console. What am I doing wrong (or not understanding) that is preventing me from seeing the JSON response in my terminal after I run the curl command? -
getting input from click event django/javascript
I have an html file that's a dataframe class. I added click event to each row using javascript after lots of reading online. What i am having trouble with, is using that click event as input into Django. Eventually, I want to be able to query a database that I am calling withing the views.py. As you can see, the sample html file contains rows of names. Hence, when the user clicks the row, i want to be able to use the first name, last name, state, address and zip as input within views.py. Sample code attached below: #sample HTML file <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th>first</th> <th>LastName</th> <th>Address</th> <th>zip</th> <th>State</th> </tr> </thead> <tbody> <tr> <td>mary</td> <td>poppins</td> <td>3345 leanie rd</td> <td>28277</td> <td>PA</td> <tr> <td>honas</td> <td>bond</td> <td>1123 cavalry st</td> <td>38788</td> <td>GA</td> <script> function addRowHandlers() { var table = document.querySelector(".dataframe"); var rows = table.getElementsByTagName("tr"); for (i = 1; i < rows.length; i++) { var currentRow = table.rows[i]; var createClickHandler = function(row) { return function() { var cell = row.getElementsByTagName("td")[0]; var id = cell.innerHTML; alert("id:" + id); }; }; currentRow.onclick = createClickHandler(currentRow); } } window.onload = addRowHandlers(); </script> #views.py def query_result(request): fname = request.GET(//what do I type here?//) -
Django template get element in list of dictionary by index
I have the following: item = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}] In django template I would like to display the price of the first element: 15.52 I am already sending the size of item list so I am doing: {{i.item|index:forloop.counter0}} => This gets me {'itemCode': 'AZ001', 'price': 15.52} If I want price, what can I do? Doing {{i.item|index:forloop.counter0.price}} is giving me invalid key price at index 0. Any solution? -
Django ManyToManyField initializes with all objects by default
I have 2 classes, Player and Game. Players can own multiple games, so we are using a m2m relation inside the Player model: class Player(models.Model): games = models.ManyToManyField(Game) My problem is, when a new Player registers, for some reason they get all of the game objects that have been added to the database. How can I make it so the new player would initially have no games? -
Autocomplete with field related to ContentType
I need some help with an issue that I am not able to resolve on my own. So in this model, a tenancy document can either have a ForeignKey with building or property. I can't figure out how to add autocomplete fields to contenttype and in the dropdown, I just see building and property in admin form. I want to see building names and property names. I learned about autocomplete fields in Django 2.0, it's awesome but I don't know how can I use something like that in this particular case or if there is a better way to do this? Model: class TenancyDocument(models.Model): KINDS = Choices('Tenancy Agreement', 'Stamp Duty', 'Inventory List') id = FlaxId(primary_key=True) kind = StatusField(choices_name='KINDS') start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) content_type_limit = Q( app_label='properties', model='building') | Q( app_label='properties', model='property') content_type = models.ForeignKey( ContentType, limit_choices_to=content_type_limit, on_delete=models.CASCADE, verbose_name='Lease type' ) object_id = FlaxId(blank=True, null=True) content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.kind -
Django 1.11 - Create auth.user using class based views
I am building a custom admin that does CRUD operations on the models. While I was just using the default admin I didn't need to go into very advanced stuff. However, searching for info on what is the best approach on creating users, I found that it seems complicated to do this, especially using the class based views. The multiple inheritance makes it very difficult to sink into the codebase to understand outside-in what's going on. The main problems: The example on generic editing views is very basic and doesn't go into handling and validating passwords for example. Building the template requires using something like widget-tweaks to properly display the form fields, labels and the possible validation. What is the best practice here? I couldn't find how exactly should I handle the validation using the generic create Some complete example on a simple CRUD for the auth.user model would do a great amount of good to all of us Django newbies. Thanks -
How can i use prefetch_related in self related model
Hi i have Menu model which has ForeignKey named parent related with itself. If parent is None it means this menu is parent menu if it shows another Menu object it means it is submenu for its parent(many-to-one relation) Here is my problem i want to get all menus with its submenus using prefetch_related but i can not get it. How can i do it? Note: I do not want to get submenus going database each time in for menu Here is my model class; class Menu(models.Model): title = models.CharField(max_length=30) language = models.ForeignKey(Language) parent = models.ForeignKey("self", default=None, blank=True, null=True) href = models.CharField(max_length=255, default="#") menutype = models.CharField(max_length=50, default="gui") icon = models.CharField(max_length=100, default="chevron-right") order = models.IntegerField(default=0) target = models.CharField(max_length=50, default="_self") Here is my query; pm2 = Menu.objects.filter(parent=None, language__code=language, menutype=menutype).prefetch_related("submenus").order_by("order") for p in pm2: print(p.title) print(p.submenus) in here when i print the submenus the result is app.Menu.None