Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
filter correctly by client Date a DateTime UTC field
I have a Django API, where i want to filter by date a DateTimeField. I store everything in the database in UTC format. date_created = DateTimeField(auto_add=now) For example: A user in the frond end selects a date in date picker: 09/22/2017 ( which i send to django as 2017-09-22 ) and i want to filter down every record thats less or equal for this date. client_date= request.POST.get('client_date') books = Books.object.filter(date_created__lte=client_date) But will this date, I'm not filtering in UTC, and i don't get the correct results, i need somehow to convert client_date to UTC format from 'America/Chicago' but i dont know how -
Django Querying the Database
Here's my Answer Model, class Answer(models.Model): likes = models.ManyToManyField(User, related_name='answer_likes') timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) I wants to filter out the Answers which received Maximum likes in last 24 Hours. How can I do that in view? Thank You :) -
TypeError: getattr(): attribute name must be string in Django
I'm writting a Django blog. I registered two models in Django admin (Category, Post). I wanted to add a new post with some category but I got following error: Internal Server Error: /admin/blog/post/add/ Traceback (most recent call last): File "/home/pecan/env/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/pecan/env/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/pecan/env/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pecan/env/lib/python3.4/site-packages/django/contrib/admin/options.py", line 551, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/pecan/env/lib/python3.4/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/pecan/env/lib/python3.4/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/pecan/env/lib/python3.4/site-packages/django/contrib/admin/sites.py", line 224, in inner return view(request, *args, **kwargs) File "/home/pecan/env/lib/python3.4/site-packages/django/contrib/admin/options.py", line 1508, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/pecan/env/lib/python3.4/site-packages/django/utils/decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "/home/pecan/env/lib/python3.4/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/pecan/env/lib/python3.4/site-packages/django/utils/decorators.py", line 63, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/pecan/env/lib/python3.4/site-packages/django/contrib/admin/options.py", line 1408, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/home/pecan/env/lib/python3.4/site-packages/django/contrib/admin/options.py", line 1440, in _changeform_view if form.is_valid(): File "/home/pecan/env/lib/python3.4/site-packages/django/forms/forms.py", line 183, in is_valid return self.is_bound and not self.errors File "/home/pecan/env/lib/python3.4/site-packages/django/forms/forms.py", line 175, in errors self.full_clean() File "/home/pecan/env/lib/python3.4/site-packages/django/forms/forms.py", line 386, in full_clean self._post_clean() File "/home/pecan/env/lib/python3.4/site-packages/django/forms/models.py", line 414, in _post_clean … -
How to filter a nested filed averaged on Django Rest Framework?
My serializer is made with an aggregation of a nested field, and I compute an average of a number on these nested objects. The Question object is nested with a Difficulty_Question Object (a 'ForeignKey' relation on the Difficulty_Question Object). Difficulty_Question have a 'difficulty' field that I averaged and aggregated on the Question object. (see get_difficulty function) I would like to filter the Question object with a range of difficulty. My serializer looks like: serializer.py: class QuestionListSerializer(ModelSerializer): difficulty = serializers.SerializerMethodField() def get_difficulty(self, obj): average = obj.difficulty_questions.all().aggregate(Avg('difficulty')).get('difficulty__avg') if average is None: return 0 return average class Meta: model = models.Question fields = ( 'id', 'name', 'difficulty', ) I try to filter this django object by difficulty, but all I can do is filtering all the objects of the nested field, not the average of all the objects.. view.py class QuestionFilter(FilterSet): difficulty_questions__difficulty__gt = django_filters.NumberFilter(name='difficulty_questions__difficulty', lookup_expr='gt') difficulty_questions__difficulty__lt = django_filters.NumberFilter(name='difficulty_questions__difficulty', lookup_expr='lt') class Meta: model = models.Question fields = {'difficulty_questions__difficulty': ['lt', 'gt']} class QuestionViewSet(ModelViewSet): queryset = models.Question.objects.all() serializer_class = serializers.QuestionSerializer action_serializers = { 'retrieve': serializers.QuestionSerializer, 'list': serializers.QuestionListSerializer, 'create': serializers.QuestionSerializer } filter_class = QuestionFilter def get_serializer_class(self): if hasattr(self, 'action_serializers'): if self.action in self.action_serializers: return self.action_serializers[self.action] return super(QuestionViewSet, self).get_serializer_class() I also use different serializers for the detail and … -
How to get only latest record on filter of foreign key django
I have a table like this Event table | id | status | date |order(FK)| | 1 | Planned | 05-02-2015 | 1 | | 2 | Delivered | 04-02-2015 | 2 | | 3 | Packed | 03-02-2015 | 3 | | 4 | Return | 06-02-2015 | 1 | I want output like this | id | status | date |order(FK)| | 2 | Delivered | 04-02-2015 | 2 | | 3 | Packed | 03-02-2015 | 3 | | 4 | Return | 06-02-2015 | 1 | I tried with query = Event.objects.annotate(order_num=Max('date')) but didn't got the expected result. How can i achieve this output -
wagtail django list index out of range
Can you please help me with this issue. I am trying to add show only tranlated menu title. And adding this code to my tags file: @register.inclusion_tag('home/tags/top_menu.html', takes_context=True) def top_menu(context, parent, calling_page=None): request = context['request'] language_code = request.LANGUAGE_CODE menuitems = parent.get_children().live().in_menu().filter(title = language_code)[0].get_children() for menuitem in menuitems: menuitem.show_dropdown = has_menu_children(menuitem) menuitem.active = (calling_page.path.startswith(menuitem.path) if calling_page else False) return { 'calling_page': calling_page, 'menuitems': menuitems, 'request': context['request'], } But I am getting this error on page : list index out of range and highlighted code {% top_menu parent=site_root calling_page=self %} Using Wagtail 1.12 and Python 3.6.2 -
How to programmatically execute WHEN and THEN on MySQL update using Python and Django?
I would like to update multiple rows in one single query by using UPDATE CASE scenario in mySQL. I am building my web app using python and Django. Here is my code: UPDATE order SET priority_number = CASE priority_number WHEN 2 THEN 3 WHEN 3 THEN 4 WHEN 1 THEN 5 WHEN 4 THEN 2 WHEN 5 THEN 1 END So this single query will update all field as I desire. My question is, how can I program this if I have an unknown number of rows to update? Lets say all these numbers comes from an array that I will pass into my views and I don’t know how many WHEN and THEN statement I need to write? thanks for your help! -
Django Models: Linking recipes and keeping track of quantities
Problem Description Suppose I have a database with multiple models running with a Django front-end. One of the tables in the Inventory. The inventory consists of entries with the following specifications: class InventoryItem(models.Model): item_name = models.TextField(max_length=10) #apple, orange, cilantro, etc... item_quantity = models.DecimalField(...) The next model will be to describe what is made with those ingredients class Product(models.Model): product_name = models.TextField(...) product_description = models.TextField(...) The ProductItem model also needs to keep track of the ingredients taken from inventory by specifying the InventoryItem and the quantity used from that inventory item used. Previous Experience In a previous experience, I have done something similar with EntityFramework in C# with MySQL. The way I achieved that was using another table/model called RecipeElement, where each one of those would be foreign-keyed to a ProductItem entry. The RecipeElement model looked like the following: class RecipeElement(models.Model): inventory_item = models.ForeignKey(InventoryItem, on_delete = models.CASCADE) quantity_used = models.DecimalField(...) product_item = models.ForeignKey(ProductItem, on_delete = models.CASCADE) The Issue My issue with that approach in Django is twofold: How would I retrieve the RecipeElement entries associated with a ProductItem entry How would the user input the RecipeElement entries and the ProductItem entries on one page. (The number of RecipeElements for each ProductItem … -
How to add method fields to ModelSerializer
In the DRF documentation for SerializerMethodField it gives the following usage example from django.contrib.auth.models import User from django.utils.timezone import now from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): days_since_joined = serializers.SerializerMethodField() class Meta: model = User def get_days_since_joined(self, obj): return (now() - obj.date_joined).days Unfortunately it fails in the latest release of DRF because ModelSerializer expects either fields or exclude to be present in the Meta. This presents a problem. If I list the method field in the fields list, I get an error django.core.exceptions.ImproperlyConfigured: Field name `days_since_joined` is not valid for model `User`. And if I do not include the method field or if I use fields = "__all__" or if I use exclude the method field ends up missing in the serialized data. How do I include the method field in a model serializer? -
Packing Django, Python and Chromium together
I would really like to distribute something like Electron for Python web applications build using Django framework. I didn't find a solution yet, so I would aks if there is one available. If not, how could I create one easily on my own? I use the latest versions of Django and Python. I would also use Chromium, because I have to care about accessibility for screen reader users and I know that Chromium is fully accessible to that users group. -
Cannot import form class into view
Django newbie here. My view function cannot import the PostForm class. All three py files are siblings. The Post class from model gets imported successfully though. Could you please help with this? Error Message: File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/ubuntu/workspace/django_projects/urls.py", line 1, in <module> import blog_app.blog_urls File "/home/ubuntu/workspace/blog_app/blog_urls.py", line 2, in <module> from . import views File "/home/ubuntu/workspace/blog_app/views.py", line 8, in <module> from .forms import PostForm ImportError: cannot import name PostForm views.py: from __future__ import unicode_literals from django.shortcuts import render, get_object_or_404 from .models import Post from .forms import PostForm def post_new(request): form = PostForm() return render(request, 'blog_app/post_edit.html', {'form': form}) forms.py: from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'text',) models.py: from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() def __str__(self): return self.title -
Not Null Constraint Fail
I looked at a ton of these issues on stack overflow, but none of the solutions seemed to help me. I've tried Null=True and Blank=True as well as default=None and they all give errors. Anyone have any ideas? Thanks so much! My models: class Trip(models.Model): title = models.CharField(max_length = 50) destination = models.CharField(max_length = 255) description = models.TextField() start_date = models.DateField(auto_now_add=False) end_date = models.DateField(auto_now_add=False) creator = models.ForeignKey(User, related_name="created_trips") participants = models.ManyToManyField(User, related_name="joined_trips", default=None) messages = models.ForeignKey(Message, related_name="messages", default=None ) notes = models.ForeignKey(Note, related_name="notes", default=None) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now_add = True) class Message(models.Model): content = models.TextField() author = models.ForeignKey(User, related_name="author") created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now_add = True) class Note(models.Model): content = models.CharField(max_length=45) user = models.ForeignKey(User, related_name="notes") My Views: def create(request): user = current_user(request) print user.id return render(request, 'first_app/create_trip.html') def add(request): user = current_user(request) print user trip = Trip.objects.create( title = request.POST.get('title'), destination = request.POST.get('destination'), description = request.POST.get('description'), start_date = request.POST.get('start_date'), end_date = request.POST.get('end_date'), creator = user ) print trip return redirect('/user_profile') -
Django - How refresh template after db update
I've tried implementing a hex board. Every single hex has his own field and data under each field. Right now I'm trying to set button who enable set some portion of data in the field, after page refresh. During creating the new object, the CityField object change if_electricity to True for change the final view in the template and show new information. The point is the hex table with information has no changed after templated reload. I've thought about some AJAX solution, but: 1.How? 2.Maybe there is the simplest solution? main_view.html {% extends 'base_city.html' %} {% load staticfiles %} {% block script %} <script src="{% static 'js/hex_events.js' %}"></script> {% endblock %} {% block title %}Miasto {{ city.name }}{% endblock %} {% block content %} <h1>Miasto: {{ city.name }}</h1> <h1>Mieszkańcy: {{ current_population }}/{{ max_population }}</h1> <h1>Domy: {{ house_number }}</h1> <h1>Dochody: {{ income }}</h1> <h1>Pieniądze: {{ city.cash }}</h1> <h1>{{ profile.current_turn }}/12</h1> {% if profile.current_turn <= 11 %} <button><a href="/turn_calculations">Kolejna tura</a></button> {% endif %} <button id="hex-change">Zmień hexy</button> <button id="buildPowerPlant">Zbuduj elektrownie</button> <div id="board"> <h1>Plansza wygenerowana z Djagno</h1> {{ hex_table }} </div> <div id="hexInfoBox"> <h1>Podgląd hexa</h1> {{ hex_detail_info_table }} </div> {% endblock %} board.py from .models import CityField, Residential, ProductionBuilding, PowerPlant hex_table = '' hex_detail_info_table … -
How would you implement a Generic view with the authenticated user as the context object?
Lets say I have a custom route '/some-route' with no url params so it won't have '/some-route/'. I want to create a generic view that will use the authenticated user as the context object. This is how I would do it, but I figured there might be a better way to do it. UserDetail(DetailView): def get_object(self, queryset=None): return self.request.user The biggest problem I can think of with this is that its expecting a pk kwarg to be past from the route. I don't want specify any route args though. Any ideas? Ty. -
Django 1.11 cant view the posts for the specific group?
Django Developers, I'm currently developing a web app for my school, and i'm experiencing some troubles displaying posts for a specific class, ill explain more: In my application, I have a feature where you can post to a specific group or class, whenever I post to a specific group it shows under the group detail page which basically shows the class and all the posts, here's a pic: this is the pic for the group detail so i wanted to change how the site looked and instead of having all the posts show under the group detail, i made a Anchor tag and put the href to post list, which is the file that displays the list of all the posts to that specific group(I'll provide all the files in a bit), here is a pic : this is the image for the group detail with the anchor tag But there was one probelm with this, its that once the user clicks on the POSTS anchor tag that i showed, it shows all posts that are posted even if it is not for that group, why is that? i want it, so that when the user clicks on the posts … -
User Model Primary Key
By default the User model in Django has id as a primary key. I have several other tables in my pre-existing data model that have a unique ID to each user, but the field name varies based on a job role such as CFO but we'll call this field ntname, cfontname, employee_ntname, based on three tables. I'd like to associate every username which is the ntname to the employee_ntname/cfo_ntname in the following model: class AllEeActive(models.Model): employee_last_name = models.CharField(db_column='Employee_Last_Name', max_length=50, blank=True, null=True) # Field name made lowercase. employee_first_name = models.CharField(db_column='Employee_First_Name', max_length=50, blank=True, null=True) # Field name made lowercase. employee_ntname = models.CharField(db_column='Employee_NTName',primary_key=True, serialize=False, max_length=50) # Field name made lowercase. b_level = models.CharField(db_column='B_Level', max_length=10, blank=True, null=True) # Field name made lowercase. group_name = models.CharField(db_column='Group_Name', max_length=100, blank=True, null=True) # Field name made lowercase. r_level = models.CharField(db_column='R_Level', max_length=10, blank=True, null=True) # Field name made lowercase. division_name = models.CharField(db_column='Division_Name', max_length=100, blank=True, null=True) # Field name made lowercase. d_level = models.CharField(db_column='D_Level', max_length=10, blank=True, null=True) # Field name made lowercase. market_name = models.CharField(db_column='Market_Name', max_length=100, blank=True, null=True) # Field name made lowercase. coid = models.CharField(db_column='COID', max_length=50, blank=True, null=True) # Field name made lowercase. unit_no = models.CharField(db_column='Unit_No', max_length=50, blank=True, null=True) # Field name made lowercase. dept_no = models.CharField(db_column='Dept_No', max_length=50, blank=True, … -
How can I use javascript and python to build an online game
I'm trying to build an online chess game using python, however I found out that there is an open source library for chess in javascript that has the bored and the movements I need. So this library will save me lot of time since it has the graphics ready , so my question is what framework should I use that will be suitable for my work, where javascript and html will handle the interface and python will handle the actual computing of the game and the online feature. I have looked up many frameworks like flask ,django , TurboGears but I still don't know the best fit for my work. Thanks -
Django.db.utils.OperationalError: FATAL: password authentication failed for user "mydbuser
How I created the user: mydb=# SELECT usename FROM pg_user; usename ----------- postgres mydbuser (2 rows) mydb=# alter user mydbuser with password 'myd5'; Django setting: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USER': 'mydbuser', 'PASSWORD': 'myd5', 'HOST': 'localhost', 'PORT': '', } } Thanks -
Django inline formset data not saved
I'm working in Django 1.11 I have three models, business, business_address, business_phone where business_address and business_phon are associated with business. I want to create fields for business_address as well as business_phone along with business whenever a new business is added. To achieve this, I have implemented ` models.py class Business(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE) class Meta: verbose_name = 'business' verbose_name_plural = 'businesses' db_table = 'businesses' def __str__(self): return self.name class BusinessAddress(models.Model): business = models.OneToOneField(Business, on_delete=models.CASCADE) line_1 = models.CharField(max_length=200) line_2 = models.CharField(max_length=200) city = models.CharField(max_length=200) state = models.ForeignKey(State, on_delete=models.PROTECT) postal_code = models.CharField(max_length=15) class Meta: verbose_name = 'business address' verbose_name_plural = 'business addresses' db_table = 'business_addresses' def __str__(self): return '%s, %s, %s, %s' % (self.line_1, self.line_2, self.city, self.state) class BusinessPhone(models.Model): business = models.ForeignKey(Business, on_delete=models.CASCADE) phone_number = models.CharField(max_length=15, default=None) class Meta: db_table = 'business_phones' def __str__(self): return self.phone_number forms.py class BusinessForm(ModelForm): class Meta: model = Business exclude = () BusinessAddressFormSet = inlineformset_factory( Business, BusinessAddress, form=BusinessForm, extra=1, can_delete=False ) BusinessPhoneFormSet = inlineformset_factory( Business, BusinessPhone, form=BusinessForm, extra=1, can_delete=False ) views.py class BusinessCreate(CreateView): model = Business fields = ['name', 'business_type'] def get_context_data(self, **kwargs): data = super( BusinessCreate, self ).get_context_data(**kwargs) if self.request.POST: data['business_address'] = BusinessAddressFormSet(self.request.POST) data['business_phone'] = BusinessPhoneFormSet(self.request.POST) else: data['business_address'] … -
Trying to connect Django dev server from remote
I have deployed my django application in server or machine A. I want to access my web page from machine B. My machine B runs in a virtual box and I did a ssh to machine A. I started the django development server at machine A using the command: python manage.py runserver 0.0.0.0:8000 I go to machine B try to access my webpage using: http://ip-machine-A:8000/appname/login/ However,I'm unable to connect. I have been through similar questions and I have tried all the solutions like modifying allowed_hosts in settings.py to ['*']. I also tried to ping the machine A and I got the response. And I also checked if the port is open by issuing the following command and it worked too. netstat -anp | grep 8000 Is there anything else I should work on to make this work? Or is this issue associated with Django development server. -
Django template exercise giving error
I am trying to practice an example from Madtering Django on templates The example tries to explain how dots can refer to methods of objects,can i avoid the error? This is my input from django.template import Template, Context t = Template('{{var}} -- {{var.upper}} -- {{var.isdigit}}') The error I get and the end Says django.core.exceptions.ImproperlyConfigured: Requested setting TEMPLATES, but settings are configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Please keep in mind I am beginner, Thank you for your answer -
invalid literal for int() with base 10: 'iie27cmjouht24y424g44s5qlm999vcj' in django
i have the following views.py: from django.template import loader from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.contrib.auth.decorators import login_required from student.models import CustomUser from student.forms import UserForm from django.template.context_processors import csrf from django.shortcuts import render_to_response from django.contrib.auth.signals import user_logged_in from .models import UserSession def user_logged_in_handler(sender,request,CustomUser,**kwargs): UserSession.objects.get_or_create( user=CustomUser, session_id= request.session.session_key ) user_logged_in.connect(user_logged_in_handler) def delete_user_sessions(CustomUser): user_sessions=UserSession.objects.filter(user=CustomUser) for user_session in user_sessions: user_session.session.delete() i have the following models.py: class UserSession(models.Model): user= models.ForeignKey(settings.AUTH_USER_MODEL) session=models.ForeignKey(Session) Also in models.py i have class CustomUser(AbstractUser). What's wrong in my views.py as the error says when i try to access /admin/ invalid literal for int() with base 10: 'iie27cmjouht24y424g44s5qlm999vcj' The full models.py is as follows: //models.py from django.utils import timezone from django.conf import settings from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.contrib.sessions.models import Session class CustomUser(AbstractUser): addr1= models.CharField(max_length=20) addr2= models.CharField(max_length=20) city= models.CharField(max_length=20) state= models.CharField(max_length=20) country= models.CharField(max_length=20,choices=country_choices) pincode= models.IntegerField(default=0,blank=True,null=True) securityq= models.CharField(max_length=20) securitya= models.CharField(max_length=20) class userresp(models.Model): uid=models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,null=True) resp=models.CharField(max_length=20) datetime=models.DateTimeField(default=timezone.now) def __unicode__(self): return u"{} {}".format(self.uid,self.datetime) class Meta: db_table="userresp" class UserSession(models.Model): user= models.ForeignKey(settings.AUTH_USER_MODEL) session=models.ForeignKey(Session) what can i do here? -
Interaction between models in django admin(app financeira)
I'm developing a cash flow application, where I have regions and each region can raise n values per month. I would like to know if it is possible to store the sum of the collection posted in the table of movements in a balance table automatically by django admin. enter image description here -
Django user sessions browser quit not ending session
I am using the following library https://github.com/Bouke/django-user-sessions to get the ability to end my session on the fly. When I am quitting the browser(not closing but ending the browser running task) the user session does not end. I tried using SESSION_EXPIRE_AT_BROWSER_CLOSE = True thinking that the library might leverage it but it doesn't work Thank you. -
Django recursive child parent queryset
I have a hard time to connect a RawQerySet to one of my models. I searched but could not find anything helpful. I'm working with two tables: Table 1. is a "part" table, contains all kind of parts (BM-), plus "machine-build" names, like B1 Bowling Machine: class Part(models.Model): part_id = models.AutoField(primary_key=True) part_children = models.ForeignKey(Part_Part, blank=True, null=True) part_number = models.CharField(default='part number here', max_length=120) part_description = models.TextField(default='text here', null=True) part_revision = models.TextField(default='text here', null=True) Table 2. a "part_part" is a parent-children connection table. For example: part_id 205 is a parent machine-build, it has no parent itself because it is top level, therefore in "part_part" table part_id_parent is NULL. The same time part_id 47 is a child of part_id 205. I can have parts (like Arduino UNO) with one or more parents. This way I can have more levels. class Part_Part(models.Model): part_part_id = models.AutoField(primary_key=True) part_id_parent = models.IntegerField(null=True) part_id_child = models.IntegerField() part_qty = models.IntegerField(null=True) I managed to get a recursive query working with PostgreSQL to find the relations: class PartPartQuerySet(models.query.QuerySet): def recursive_query(self, parent_id): if parent_id is None: exp = " is NULL" sql = '''with recursive rel_tree as ( select part_part_id, part_id_parent, part_id_child, 1 as level, array[part_part_id] as path_info from inventory_part_part where part_id_parent ''' …