Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get full User object on post_save signal
I am new to signals. What I want to do could be done on views pragmatically and perhaps signals is not the way to go but regardless, I am having issues with the signal. I have a User model (custom) and UserIdentities model. When a new user is created, 3 identities will be generated and saved in UserIdentities model: User(models.Model): fields... UserIdentities(models.Model): user = models.ForeignKey(User) @receiver(post_save, sender = User) def user_created(sender, instance, created, raw, **kwargs): if created: # generate three dept identities and save in UserIdentities model identities = generate_identiteies(instance) The issue I am having now is that instance is username (a single string), not an instance of User object with all attributes of the user. In the documentation, it says instance is the object that was created but here I am getting only the username of the user created but need a couple of other fields needed for identity generation -
how to remove duplicate queries in django admin add_view/change_view?
i got 2 duplicate queries in django admin add_view/change_view because of foreign key fields in my model. how to remove these duplicate queries in django admin add_view/change_view. not the list_view. -
Pass OneToOne relationships to Django Templates
I am trying to setup a OneToOne relationship in Django in order to show data from TableA and TableB for a specific record. I am having issues figuring out how to display it in my view, examples are out there but some seem a bit outdated or have solutions that I am not familiar with. I have tried with some different calls in the views file as well as in my templates file without any luck, any input would be highly appreciated! My models.py from django.db import models # Create your models here. class tableA(models.Model): created = models.DateTimeField(default=None) published = models.CharField(max_length=50, default=None) publisher = models.CharField(max_length=50, default=None) code = models.CharField(max_length=25, null=True, unique=True) class Meta: db_table = 'tableA' unique_together = (("publisher", "published"),) def __str__(self): return self.created class tableB(models.Model): tableA = models.OneToOneField(tableA, on_delete=models.CASCADE, primary_key=True, default=None) code = models.CharField(max_length=50, default=None, null=True) url = models.CharField(max_length=100, default=None, null=True) class Meta: managed = True def __str__(self): return self.tableA.code My views.py def nani(request): data = TableA.objects.all() return render(request, 'site/home.html', {'data':data}) My template {% for test in data %} <tr> <td>{{ test.published }}</td> <td>{{ test.publisher }}</td> <td>{{ test.TableB.url }}</td> </tr> {% endfor %} -
Class relationship in Django model
My project(Django Rest Framework) is blog app where logged in users can Post some texts and any logged in users can add comment to Posts. What are the changed I need to make in the Post and Comment class to establish the logic ? from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings class User(AbstractUser): #User model class Post(models.Model): postdata = models.CharField(max_length=100) owner = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) class Comment(models.Model): body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) -
What does this html tag mean in django's example?
This is django's polls demo, and most are well documented. However, in this part: https://docs.djangoproject.com/en/3.0/intro/tutorial04/ <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a> The documentation doesn't say anything about this part: vote{{ choice.votes|pluralize }} And from the generated html page, I can't see what's the role of this piece? -
Which django field should be used for a time counter?
I need a field in the model for a required work hours. For example, with default value 40 hours. Which field I should use? -
Sending pop-up notification to specific users in Django
I am working on a notification part of a Django project where 1. an user can create a project (selecting users to work with), and 2. create a meeting (the creator can edit or cancel by changing the meeting location or time), and 3. invitees can vote for a preferred time and eventually decide the meeting time where the majority agrees with. My part is to send any types of notification to those invitees when cases 1-3 happen. For example in cases 1 and 2, I wanna implement the way to give invitees pop-up notifications when the creator submits the form, and for case 3, I want invitees to be notified when each invitee votes. class Notification(models.Model): created = models.DateTimeField(auto_add_now=True) text = models.TextField() users = models.ManyToManyField(User, through='NotificationUser') class NotificationUser(models.Model): created = models.DateTimeField(auto_add_now=True) updated = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) notification = models.ForeignKey(User,on_delete=models.CASCADE) read = models.DateTimeField(null=True, blank=True) I have written models for the notification (feel free to give me advice for better models), but I can’t really think of the best way to send those invitees pop-ups (In view). Even if it’s not a pop-up notification, as long as you have a better or easier idea to implements, please help me! … -
Argument must be int or float
When I typed "Product.objects.get(id=1) on the python shell, I got this error "TypeError: argument must be int or float". What could be the cause of this error? -
Bootstrap scrollbar slipped behind content
I am working on a webpage using Bootstrap 4 and after fixing the appearance of a horizontal scrollbar on mobile devices by adding overflow-x:hidden to the html tag I noticed that the main y scrollbar looked weird and was not clickable most of the time anymore (normally it can be pulled with the left mouse button, but it does not react to clicks now. It does, however, register clicks on content that is behind the scrollbar!). It has definitely not been like this for long, but I have not the faintest idea what caused this change since I did not touch any z-index or scrollbar settings... I am using Chrome and it should display the standard, unstyled scrollbar, which does not look like this. Can anyone tell me what happened and how to fix it?! -
Dropdown navbar menu on my Django/Bootstrap 4 website works everywhere except on the home page
As the title says, I have a dropdown menu on my site. At first it only worked on the homepage and nowhere else until I realised I didn't include the link to the Bootstrap JavaScript framework in the base.html file. So I included it and now the dropdown menu works everywhere except on the homepage. I feel like this is a simple fix and is just staring me in the face but it has me stumped. Any help is appreciated. Here is the base.html {% load static %} <!DOCTYPE html> <html> <head> <title>TUD Cinemas</title> <!-- My own CSS Link --> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <!-- Bootstrap CSS Link --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <!-- Google font link --> <link href="https://fonts.googleapis.com/css?family=Montserrat:500&display=swap" rel="stylesheet"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light sticky-top"> <div class="container"> <a class="navbar-brand" href="{% url 'home' %}"> <img src="/static/images/TUDC_logo.png" class="luke_logo"> </a> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'home' %}">Home<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'movies' %}">What's on</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'blog' %}">Blog</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'news' %}">News</a> </li> {% if request.user.is_authenticated %} <!-- Dropdown Menu --> <li class="nav-item dropdown multi-level-dropdown"> <a href="#" id="menu" data-toggle="dropdown" … -
Django admin page looks different when deployed to the web host
I have seen this problem posted and people have answered in a number of ways, which I have tried, but I am still having issues with the deployed version looking different than when it is on localhost. I tried using the collectstatic command, but it still looks weird and ugly. I removed some things from this post, such as the secret key and database info. Here is my settings.py: ALLOWED_HOSTS = ['acrms-mis446-2020.herokuapp.com', 'localhost'] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'carts', 'orders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mis446.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mis446.wsgi.application' # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') STATIC_URL = '/static/' LOGIN_REDIRECT_URL = 'ACRMS-Home' -
Table Pagination [Bootstrap - Django]
I'm working on a django-bootstrap project and i'm having some trouble with the bootstrap's table pagination, it won't appear on my template. I'm using one of the default's bootstrap tables with my own styles, and i wanted to ask you guys for your help to give my table the pagination it needs. <table id="table1" class="table table-bordered table-striped" style="width:1200px; margin-left:-45px"> <thead > <tr> <th class="header1"> </th> <th class="header1">ID Riesgo</th> <th class="header1">Código Riesgo</th> <th class="header1">Característica</th> <th class="header1">Evento</th> </tr> </thead> <tbody> {% for riesgos in riesgos %} <tr style="height: -2px;"> <td style="text-align:center;"> <div class name="checkboxWrapper"> <input type="checkbox" id="check" hidden="true" style="margin-top: 10px;"/> <label for="check" class="checkmark" ></label> </div> </td> <td style="color:#A9A9A9 ;">{{riesgos.id_ri}}</td> <td style="color:#A9A9A9;">{{riesgos.cod_ri}}</td> <td style="color:#A9A9A9;">{{riesgos.caracterisitica}}</td> <td style="color:#A9A9A9;">{{riesgos.evento}}</td> {% endfor %} </tr> </tbody> </table> Thanks everyone! -
Python Elasticsearch - error during --populate
could someone help me understand this error below? Your operating system name and version: [enter image description here][1] Any details about your local setup that might be helpful in troubleshooting: elasticsearch==6.3.1 elasticsearch-dsl==6.1.0 django-elasticsearch-dsl==0.5.1 Detailed steps to reproduce the bug: [enter image description here][1] Lib: https://github.com/sabricot/django-elasticsearch-dsl Code: documents.py from elasticsearch_dsl import analyzer, tokenizer from django.utils.html import format_html from django.db.models.query import QuerySet from apps.comprasnet.models import PregaoItens, PregaoWeb, UasgWeb, Modalidade, TermoHomologacao pregaoitens = Index('pregaoitens') pregaoitens.settings( number_of_shards=1, number_of_replicas=0 ) @pregaoitens.doc_type class IndexPregaoItens(DocType): licitacao = fields.ObjectField(properties={ 'licitacao_id': fields.TextField(), }) uasg = fields.ObjectField(properties={ 'co_uasg': fields.IntegerField(), 'uf': fields.TextField(), }) modalidade = fields.ObjectField(properties={ 'codigo': fields.IntegerField(), }) # index.map.totalfields.limit termo = fields.ObjectField(properties={ 'id': fields.TextField(), }) descricao = fields.TextField( fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField() }, fielddata=True, analyzer='keyword' ) html_strip = analyzer( 'html_strip', tokenizer="whitespace", filter=["lowercase", "snowball", "stemmer", "asciifolding", "trim"], char_filter=["html_strip"] ) descricao_comp = fields.TextField( analyzer="standard", fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField() } ) uasg_name = fields.TextField( analyzer=html_strip, fields={'raw': fields.KeywordField()} ) uf = fields.TextField(fielddata=True) valor_estimado = fields.FloatField() lance_per = fields.FloatField() desconto_nego = fields.FloatField() lance_real = fields.FloatField() valor_nego = fields.FloatField() valor_equalizado = fields.FloatField() valor_total = fields.FloatField() bec_proposta_valor = fields.FloatField() unidade_id = fields.TextField(fielddata=True) class Meta: model = PregaoItens related_models = [PregaoWeb, UasgWeb, Modalidade, TermoHomologacao] fields = [ 'id', 'nu_pregao', 'modalidade_desc', 'objeto', 'dt_entrega_proposta', 'dt_abertura_proposta', 'dt_homologacao', 'download_link', … -
Updating only certain object's div in Django using jQuery
I am trying to update the DOM, whenever a user likes a post and displays the number of likes on a post. However, I realized my function will update all the classes on the pages and not only the certain post being liked (When a user clicks on thmbs up, all the thumbs up buttons change to dumbs down) my function for changing the like: function like_post() { // newly added $('#like-section #likeBtn').on("click", function (e) { e.preventDefault(); if($("#like-section #likeBtn i").hasClass("fa-thumbs-up")){ ($("#like-section #likeBtn i").removeClass("fa-thumbs-up")) ($("#like-section #likeBtn i").addClass("fa-thumbs-down")) } else { ($("#like-section #likeBtn i").removeClass("fa-thumbs-down")) ($("#like-section #likeBtn i").addClass("fa-thumbs-up")) } }); // end } my posts HTML template in Django: {% load static %} <link rel="stylesheet" href="{% static 'css/post/style.css' %}"> <script src="{% static 'js/like-api.js' %}"></script> <script src="{% static 'js/post.js' %}"></script> {% for post in posts %} <script> $(document).on('click', '.post-detail-clickable-details-view', function () { var url = $(this).attr("data-url") document.location.href = url }); </script> <div class="row ml-2"> <div class="col-sm-2"> <div class="float-right mb-3 mt-3"> <div> <img class="img-create-post rounded-circle mr-2" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg" alt="Profile image"> </div> <div> <p class="text-muted post-card-date small mr-2">{{ post.get_created_on }} ago</p> </div> </div> </div> <div class="col-md-10" style="margin-left: -1.6rem;"> <div class="card rounded-0 mb-3 mt-3"> <div class="card-header bg-transparent" style="height: 3rem;"> <h5 style="margin-bottom: 0px;"> <a class="text-dark" style="text-decoration: none;" href="{% url … -
Serve medias as static django
I have a template where I want to iterate through the Massage objects of the Massage Model. I'm using a for loop in my gabarit. My problem is that I need to upload the image for each massage and then serve it with boto3 using S3 storage. This make the loading of my page longer. Is there a way to store these media files as statics? So I can serve it with Whitenoise? class Massage(models.Model): nom = models.CharField(max_length=120) nom_traditionnel = models.CharField(max_length=120, default="", blank=True) description = models.TextField() image = models.ImageField(blank=True, null=True, upload_to='image/') Thanks for you help. -
Django Model Form not saving NULL data
I have the following form, view and model form, the Django version is 3.0 and the original DB is written in PostgreSQL, the form is submitted via ajax. class Model(models.Model): depth = models.FloatField(blank=True, null=True) from_field = models.FloatField(blank=True, null=True) to = models.FloatField(blank=True, null=True) interval = models.FloatField(blank=True, null=True) class Meta: managed = False class Form(forms.ModelForm): class Meta: model = Model fields = ['depth', 'from_field', 'to', 'interval'] @csrf_exempt def AddData(request): form = Form(request.POST) if form.is_valid(): form.save() When AddData is executed there is no errors but with the data being something like: depth=30, from_field=null, to=null, interval=null The data saved in the database is: depth=30, from_field=0, to=null, interval=null Could this be because the model has the parameter managed=False? I've checked the data sent by the template and when it's received by the view and the null data reflects correctly in DB except for from field. -
Django filter: Many to Many specific field to custom Group field
This is probably not the best way to go about user permissions- though I have a list of User Groups that contain names of Markets and a custom field built in containing the "Market_id". Within the models I am filtering, I have a ManytoMany relationship linked to another model named "Markets". The "Markets" model also has a "market_id" field. How can I go about giving the user only the objects that are within their "Market" or group?: Models I am filtering: class Opportunity(models.Model): opportunityid = models.CharField(max_length=500, blank=True) market = models.ManyToManyField('Market', related_name ='market', blank= True) Market model- M2M relationship: class Market(models.Model): marketname = models.CharField(max_length=500) market_id = models.CharField(max_length=100, blank=True) def __str__(self): return self.marketname My attempt at the queryset- currently returns a blank queryset, even though my user has permissions for all markets or groups: class projectViewSet(viewsets.ModelViewSet): serializer_class = ProjectSerializer authentication_classes = [SessionAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self): user = self.request.user groups = user.groups.all() finalgroups = [] for g in groups: finalgroups.append(g.market_id) queryset = Opportunity.objects.all() queryset = queryset.filter(market__market_id__in = finalgroups) return queryset Thanks for your time! -
Django Content Security Policy Allow Sitemap.xml and Robots.txt
I am using https://django-csp.readthedocs.io/en/latest/ and I cannot figure out how to get the content security policy to allow the sitemap.xml file and robots.txt file. The sitemap.xml file I am generating automatically using https://docs.djangoproject.com/en/3.0/ref/contrib/sitemaps/. The robots.txt file I am using https://django-robots.readthedocs.io/en/latest/ CSP error (applies to both): Refused to apply inline style because it violates the following Content Security Policy directive: "style-src..... Sitemap.xml: prepareWebKitXMLViewer@VM709:30(anonymous)@VM709:383 <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> ........ "use strict"; var nodeParentPairs = []; var tree; function prepareWebKitXMLViewer() { var html = createHTMLElement('html'); var head = createHTMLElement('head'); html.appendChild(head); var style = createHTMLElement('style'); style.id = 'xml-viewer-style'; head.appendChild(style); var body = createHTMLElement('body'); html.appendChild(body); var sourceXML = createHTMLElement('div'); sourceXML.id = 'webkit-xml-viewer-source-xml'; body.appendChild(sourceXML); var child; while (child = document.firstChild) { document.removeChild(child); if (child.nodeType != Node.DOCUMENT_TYPE_NODE) sourceXML.appendChild(child); } document.appendChild(html); var header = createHTMLElement('div'); body.appendChild(header); header.classList.add('header'); var headerSpan = createHTMLElement('span'); header.appendChild(headerSpan); headerSpan.textContent = "This XML file does not appear to have any style information " + "associated with it. The document tree is shown below."; header.appendChild(createHTMLElement('br')); tree = createHTMLElement('div'); body.appendChild(tree); tree.classList.add('pretty-print'); window.onload = sourceXMLLoaded; } Robots.txt: User-agent: * Disallow: Host: example.com -
Global Variable Not Updating In Django View
I am trying to loop through users on a certain AJAX request and assign a different value to a global variable once I get the data returned to my django view from AJAX. Inside the if statement, the variable prints correctly, however, when I try to access it in the view's context dictionary, it retains it's old value and does not update. views.py def view_profile(request): g = Friend.objects.all() j = forms.FriendForm() s = forms.SearchForm() h = UserProfileInfo.objects.all() global term term = [] global r r = [] global e e = h[0] global friend_arr friend_arr = [] global messages messages = [] if len(g) != 0: for x in g: if x.user == request.user.username: friend_arr.append(x) else: pass if request.method == "POST": s = forms.SearchForm(request.POST) j = forms.FriendForm(request.POST) if request.is_ajax(): if list(request.POST)[0] == 'friend': friend = request.POST['friend'] for x in range(0, (len(h) - 1)): if str(h[x]) == str(friend): e = h[x] break else: pass elif list(request.POST)[0] == 'to_be_messaged': t6t6 = request.POST['to_be_messaged'] new_arr = t6t6.split('+') global action global user action = new_arr[0] user = new_arr[1] messages = MessageModel.objects.filter(user=request.user.username, to_user=user) else: d = MessageModel.objects.get_or_create( user=request.user.username, to_user=user, message=request.POST['message_text'], )[0] d.save() # return HttpResponse('') print(e) if s.is_valid(): term = ArtistCount.objects.filter(user__icontains=(s.cleaned_data['friend'])) if j.is_valid() and request.POST.get('sReq') is … -
NOT NULL constraint django
I am trying to create a cart model using ForeignKey relation with User. My models.py: class cart(models.Model): item = models.OneToOneField(products, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, blank=True, default=None, on_delete=models.CASCADE) def __str__(self): return self.item.name I am getting a error like this: django.db.utils.IntegrityError: NOT NULL constraint failed: new__mall_cart.user_id I have provided null=True as well as blank=True and the superuser is created with the name of admin. What is issue here? Also, I don't want the user field to be null neither it to be blank. How can I resolve this? -
Get count from other url (DRF)
Early, I did create answer - Count objects using Django Rest Framework Now, I want to add a field with an image URL. I want to create like this - { "brand" : "Some name", "count": Int, "image": "some path to image.jpg" } How to create it? -
Different login views with Custom User
My goal is to have two views for login: one with email and password, and another with username and password. Created a custom user class named MyUser extending from AbstractBaseUser. In that user class, stablished USERNAME_FIELD = 'email' Django by default uses the username field for authentication purposes of a user. When i want users to login with email, that's easy now. But how can I do to create another view that logs in with just username and password (instead of the email)? -
why django admin shows 2 duplicated queries for foreignkey field in djang debug toolbar?
i have a model which use foreignkey. for example POST model use foreignkey for Category Model. when i use django debug toolbar in django admin, it shows 2 duplicate times/ 2 similar queries for foreignkey field. what is the problem and how to fix it? -
Why does my page display all blog entries even after applying pagination
Please help here. I am displaying blog entries in a page in my application. All entries keeping displaying even after setting the views to display 2 entries per page. Views.py page = request.GET.get('page', 1) paginator = Paginator(blog_post,2) try: blog_page = paginator.page(page) except PageNotAnInteger: blog_page = paginator.page(1) except EmptyPage: blog_page = paginator.page(paginator.num_pages) context = { 'blog':blog_page, 'page':page, } return render(request, 'webpages/blog.html', context=context) Blog.html <div class="blog-pagination"> {% if blog.has_other_pages %} <ul class="justify-content-center"> {% if blog.has_previous %} <li><a href="?page={{ blog.previous_page_number }}"><i class="icofont-rounded-left"></i></a></li> {% else %} <li class="disabled"><i class="icofont-rounded-left"></i></li> {% endif %} {% for i in blog.paginator.page_range %} {% if blog.number == i %} <li class="active"><a href="">{{ i }}</a></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if blog.has_next %} <li><a href="?page={{ blog.next_page_number }}"><i class="icofont-rounded-right"></i></a></li></a></li> {% else %} <li class="disabled"><i class="icofont-rounded-right"></i></a></li></li> {% endif %} </ul> {% endif %} -
Can't make Django raw sql working correctly
I need to make inner join query like this: SELECT * FROM accounting_supplier as s LEFT JOIN ( SELECT position, supplier_id FROM accounting_supplierposition WHERE user_id = %s ) as sp on sp.supplier_id = s.id ORDER BY sp.position", [request.user] Models look like: class Supplier(models.Model): name = models.CharField(max_length=512) short_name = models.CharField(max_length=100, unique=True) class SupplierPosition(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) position = models.PositiveIntegerField() I've tried different approaches but no one gives the result I want. There is a way described here: Django Left Outer Join but distinct does not work with MySQL, so I decided to use RAW. But it seems that ordering doesn't work correctly. If I copy/paste sql from my code to mysql command line it works fine but in Django it does make selection but no order. Any suggestions? Thank you.