Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: detect what models was used in query
TL;DR: Need to know what models was used in queries executed in some block of code I have self-made caching system that has ability to automatically drop cache when specific models get saved. The usage is (example in Django Rest framework API viewset): class UsersViewSet(ListModelMixin) model = User queryset = User.objects # Here cache decorator goes @cache_view(models_to_drop_cache=[User, UserProfile, UserPhone]) def list(self, request, *args, **kwargs): # calling the real viewset method return super().list(request, *args, **kwargs) Now when any of models [User, UserProfile, UserPhone] change, cache on that view would be dropped (it's achieved by using signal receiver of model save signal). The problem is: sometimes not all models got written to the list (somebody forgot to) and cache not being dropped when it should. I want to add some debug argument to method cache_view so in debug mode decorator gather information about models that was used in the decorated method and output the list. I've tried to look for model signals but didn't succeeded. It seems like I need to monkey-patch Django's query builder to check for table names in resulting SQL code that got executed. Maybe there is more straightforward method? -
I have a select menu and I want a query action when the user chooses an option value. I am using Django
<div class="row"> <div class="input-field col s2 offset-s1"> <select> <option value="" disabled selected>Options:</option> <option value="1">Display all</option> <option value="2">Sort by data</option> <option value="3">Sort by price</option> </select> </div> </div> How can I write the template code {% code %} and the views functions for making queries which depend by the select menu? -
Use HTML entities in django template
I want to use HTML entities in my Django template. I know that I can do something like this <th>0&ge;a&lt;10</th> and it will work correctly. But I send to my template list with that which looks like list_of_ranges = ['Name', 'Type', 'a<1', '5<a<10' .......] So in a template in for loop, I want to use &ge, &lt, and others for values that contain '>', '>=' and others. I tried to use it in the list before sending it to the template, but it's not working correctly. See below. list_of_ranges = ['Name', 'Type', 'a&lt;<1' .......] and in template fo like this {{list_of_ranges.2}} Result: a&lt;<1 Could you help, how can I resolve it? -
Can a django template call another template in Modal window?
My requirement is to a django template from another django template. the second template would open in a Modal window instead of taking me to a different page. Parent View : Basic Child View : Cancellation Can the child view template be kicked off through a modal? I am new to this so I need a sample code to achieve this. -
What is the best way to store chat Messages in Django for better performance
Currently, I am using default SQLite DB to store messages, as I am using channels... I update the Database at every send and receive a signal from WebSocket. but it would be too expensive when traffic will be large as at every send and receive I interact with Django ORM is there any other efficient way? class Room(models.Model): name = models.CharField(max_length=150) group = models.CharField(max_length=150,null=True) def __str__(self): return self.name class Message(models.Model): room = models.ForeignKey('Room',null=False,blank=False,on_delete=models.CASCADE) sender = models.ForeignKey(User,on_delete=models.CASCADE,null=True) message = models.TextField() def __str__(self): return self.message -
Django model class error when adding a new class into models
I have the following code: models.py from django.db import models class Title(models.Model): title_name = models.CharField(max_length=200) category = models.CharField(max_length= 30) class Tags(models.Model): tag1 = models.CharField(max_length=15) tag2 = models.CharField(max_length=15) tag3 = models.CharField(max_length=15) tag4 = models.CharField(max_length=15) class Videos: primo: str views.py from django.shortcuts import render, HttpResponse from django.http import HttpResponse from .models import Videos def home(request): vid = Videos() vid.primo = 'https://www.youtube.com/' return render(request, 'index.html', {'vid': vid}) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] When I run the server I get: RuntimeError: Model class home.models.Title doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Everything was working before adding class Videos() and just using: def home(request): return render(request, 'index.html') I don't understand what I should specify in the INSTALLED_APPS as I just added a new def to render a video URL inside my HTML. Why I get this error? Thanks! -
showing "Did not find any relations." though I have many tables while working in google app engine
Google App Engine Cloud Shell Terminal: SSL connection() Type "help" for help. postgres=> \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges ---------------+-------------------+----------+------------+------------+----------------------------------------- cloudsqladmin | cloudsqladmin | UTF8 | en_US.UTF8 | en_US.UTF8 | daysdb | cloudsqlsuperuser | UTF8 | en_US.UTF8 | en_US.UTF8 | postgres | cloudsqlsuperuser | UTF8 | en_US.UTF8 | en_US.UTF8 | template0 | cloudsqladmin | UTF8 | en_US.UTF8 | en_US.UTF8 | =c/cloudsqladmin + | | | | | cloudsqladmin=CTc/cloudsqladmin template1 | cloudsqlsuperuser | UTF8 | en_US.UTF8 | en_US.UTF8 | =c/cloudsqlsuperuser + | | | | | cloudsqlsuperuser=CTc/cloudsqlsuperuser (5 rows) postgres=> \c daysdb Password: psql (13.1 (Debian 13.1-1.pgdg100+1), server 12.4) SSL connection() You are now connected to database "daysdb" as user "postgres". daysdb=> \dt Did not find any relations. I don't know where I am mistaking. Is there any method to give permission to view tables or something else... and when I directly run my app using gcloud app deploy command it shows error: LINE 1: ..._header"."mob_img", "days_header"."welcome" FROM "days_hea... which means my tables are not migrated. Please help me! -
How to check if a file is csv or not?
I have a django views function that converts csv into another delimiter format. But, I just want to convert csv file and reject other files. def index(request): csv_form = '' if request.method == 'POST': csv_form = CsvForm(request.POST, request.FILES) if csv_form.is_valid(): csv_file = TextIOWrapper(request.FILES['csv_file'].file, encoding='ascii', errors='replace') #other actions I cannot use the below code because this works with only binary files, but the csv module wants to have text-mode files instead. Any alternatives to proceed with only csv files. if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') -
Is it possible to substitute an image file for a user selected upload in Django?
I have a model that has an image field with the usual create and edit pages in my Django app. However I need a copy function for the user with the functionality to copy the image in addition to some of the other fields. Now it would be possible to copy the image entirely on the server side, however this gets messy with having to delete the image if the user cancels the copy, or if the user decides to replace the copied image with a new upload. So I was wondering if there was a different way, where the image to be copied is substituted in for the usual upload? Almost like as if the image file to be copied is temporarily downloaded to the client before they interact with the copy page. Current model code for reference: import os from uuid import uuid4 @deconstructible class UploadToPathAndRename(object): def __init__(self, path): self.sub_path = path def __call__(self, instance, filename): ext = filename.split('.')[-1] filename = '{}.{}'.format(uuid4().hex, ext) return os.path.join(self.sub_path, filename) class Foo(models.Model): name = models.CharField(db_index=True, max_length=60) image = models.ImageField(upload_to=UploadToPathAndRename( 'default'), blank=True) -
Multiplying an integer and a decimal in a Django model using model expressions
I am a Django and in one of my projects, I made this model: class Piece(models.Model): order = models.ForeignKey(Order,on_delete=models.CASCADE) coil = models.ForeignKey(Cut_Material ,on_delete=models.CASCADE) piece_length = models.DecimalField(max_digits=4, decimal_places=2) prime_pieces = models.IntegerField() reject_pieces = models.IntegerField() def __str__(self): return (str(self.piece_length)) class Meta: ordering = ["-order","piece_length"] I want to be able to multiply piece_length with prime_pieces to get running meters and here is my solution: Piece.objects.annotate(running_meters = (F('reject_pieces') * F('prime_pieces')), output_field=FloatField()) I get this error: TypeError: QuerySet.aggregate() received non-expression(s): <django.db.models.fields.FloatField>. Can anyone help me with a solution, please? -
Django "Table 'myproject.auth_user' doesn't exist"
I have a bunch of tables generated in different apps in my app. Because of some issue I had to drop all the tables and create them from the scratch. one app is related for profile. One I run these commands I get an error as below: python manage.py makemigrations Operations to perform: Apply all migrations: admin, myapp, auth, cities, contenttypes, sessions, users and by this: python manage.py migrate I get: Running migrations: No migrations to apply. After all I don't see the dropped tables between database tables and consciously after run server get errors which "Table 'myproject.auth_user' doesn't exist". I also tried to remove the files in the migrations folder but does not work. Most probably these files are stored somewhere which I don't find!! Do you have any suggestion? -
How to change id field from uuid type to integer in a django model
My model as exists it has the below format: class MyModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) How it is possible to turn id to be of integer type , auto incremented and primary key? As the default behaviour of db when someone does not define at all the id field Deleting id field and running : python manage.py makemigrations python manage.py migrate raises an error of : django.db.utils.ProgrammingError: cannot cast type uuid to integer LINE 1: ...MyModel" ALTER COLUMN "id" TYPE integer USING "id"::integer Deleting the id field as it is and create again the id field as below: id = models.AutoField(primary_key=True, unique=True) and running again (now with two migration files) python manage.py makemigrations python manage.py migrate raises the same error as before. Finally, changing the data type of the id field from uuid to integer directly from the db is not a good option and may cause deployment issues. How can I make this transition and keep my db working properly? -
How to preserve key order in a Django JSONField
I am having a hard time preserving the order of keys in a JSON object stored in a Django JSONField. I have tried using a custom encoder and decoder as per the docs, but the JSON object keeps re-ordeing itself: >>>from models import MyModel >>>my_dict = {"c": 3, "b": 2, "a": 1} >>>my_model = MyModel() >>>my_model.my_field = my_dict >>>my_model.save() >>>my_model.refresh_from_db() >>>my_model.my_field OrderedDict([('a',1), ('b', 2), ('c', 3)]) I would have expected it to return OrderedDict([('c',3), ('b', 2), ('a', 1)]). Here is what I've tried so far: models.py: import collections import json from django.db import models class OrderedEncoder(json.JSONEncoder): def encode(self, o): if isinstance(o, collections.OrderedDict): encoded_objs = [ f"{self.encode(k)}: {self.encode(v)}" for k, v in o.items() ] return f"{{{','.join(encoded_objs)}}}" else: return super().encode(o) class OrderedDecoder(json.JSONDecoder): def __init__(self, *args, **kwargs): default_kwargs = { "object_pairs_hook": collections.OrderedDict } default_kwargs.update(kwargs) super().__init__(*args, **default_kwargs) class MyModel(models.Model): my_field = models.JSONField(encoder=OrderedEncoder, decoder=OrderedDecoder) Any ideas? -
Django - Modifies models field arguments
I am not sure how to make a change in my code. I have 2 models that have the same fields and I want to respect the DRY principle and make just one model with a field "type" and to filter the objects by the type field, the problem is that these models on the category field have diferent categories choices and I'm wondering if I can add a function that will decide depending on the model type which choices to attribute. the models: class Income(models.Model): class IncomeCategory(models.TextChoices): SALARY = 'SLRY', _('Salary') PROFIT = 'PRFT', _('Profit') INTEREST = 'ITRT', _('Interest') DIVIDENT = 'DVDT', _('Divident') RENTAL = 'RNTL', _('Rental') CAPITAL = 'CPTL', _('Capital') ROYALTY = 'RYLT', _('Royalty') GIFT = 'GIFT', _('Gift') OTHERS = 'OTRS', _('Others') user = models.ForeignKey(User, on_delete=models.CASCADE), name = models.ChardField(_('Income Name')max_length=50), amount = models.DecimalField(_('Income Amount'), max_digits=10, decimal_places=3) category = models.CharField(_('Category'), max_length=4, choices=IncomeCategory.choices, default=IncomeCategory.SALARY) recurrent = models.BooleanField(default=False) created_date = models.DateTimeField(_('Created Date')auto_now_add=True) updated_date = models.DateTimeField(_('Updated Date')auto_add=True) def __str__(self): return f'{self.user.username} - {self.name}' class Spending(models.Model): class SpendinCategory(models.TextChoices): UTILITIES = 'UTLT', _('Utilities') RENT = 'RENT', _('Rent') INVOICES = 'INVC', _('Invoices') SHOPPING = 'SHPG', _('Shopping') FOOD = 'FOOD', _('Food') EDUCATION = 'EDCN', _('Education') FUN = 'FUN', _('Fun') INSETMENT = 'INVT', _('Investment') OTHERS = 'OTRS', … -
CoreAPI to OpenAPI schema generation transition (Django REST Framework)
Django REST Framework 3.10 (September 2019) introduced OpenAPI based schema generation instead of CoreAPI, which has been deprecated (see release notes here). I'm creating an API using the current actual 3.12.0 version (13th October 2020). This change introduces regressions: Redundant Operation IDs, A "workaround" is required to get schema using coreapi cli command (see here), Mandatory parameters defined in serializer are not extracted in schema generation, thus I cannot use the coreapi cli command. The last point is the really problematic one. I can easily switch from the OpenAPI to the (deprecated) CoreAPI AutoSchema class changing the url parameter in get_schema_view function and adding this in settings.py: REST_FRAMEWORK = { # [...] 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', } Example Below is an example using both schema classes. models.py: class Operator(models.Model): code = models.IntegerField(unique=True, blank=False, null=False) first_name = models.CharField(max_length=45, unique=False, blank=False, null=False) last_name = models.CharField(max_length=45, unique=False, blank=False, null=False) serializers.py: class OperatorSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Operator fields = ['url', 'id', 'code', 'first_name', 'last_name'] views.py: class OperatorViewSet(viewsets.ModelViewSet): queryset = Operator.objects.all() serializer_class = OperatorSerializer permission_classes = [permissions.IsAuthenticated] Using Core API # No workaround coreapi get http://127.0.0.1:8000/api/openapi # [...] operators: { list([page]) create(code, first_name, last_name) read(id) update(id, code, first_name, last_name) partial_update(id, [code], [first_name], [last_name]) delete(id) } # … -
DJANGO - SWAGGER - Why serielizer was put into format of RESPONSE
Obviously, I am using Django to code, and want to document by drf_yasg lib its actually Swagger but the new version (I supposed so) Everything is fine, excepts that swagger automatically assume my OUTPUT or RESPONSE of my API is the Serielizers. As the image below Here is my Serializers.py class Serielizer_RecalculateDeliveryPromise(serializers.ModelSerializer): service_type = serializers.CharField(max_length = 68, min_length = 6, write_only= True) package_type = serializers.CharField(max_length = 68, min_length = 6, write_only= True) origin_handover_point = serializers.CharField(max_length = 68, min_length = 6, write_only= True) destination_handover_point = serializers.CharField(max_length = 68, min_length = 6, write_only= True) class Meta: model = Input_RecalculateDeliveryPromise fields = ['service_type', 'package_type', 'origin_handover_point', 'destination_handover_point'] Here is my models.py class Input_RecalculateDeliveryPromise(models.Model): service_type = models.CharField(max_length = 255, db_index = True, default = ) package_type = models.CharField(max_length = 255, db_index = True) origin_handover_point = models.CharField(max_length = 255, db_index = True) destination_handover_point = models.CharField(max_length = 255, db_index = True) Here is my views.py class recalculate_delivery_promise(generics.GenericAPIView): serializer_class = Serielizer_RecalculateDeliveryPromise def post(self, request): request_data = json.loads(request.body) serializer = self.serializer_class(data=request_data) serializer.is_valid(raise_exception=True) service_type = request_data["service_type"] package_type = request_data['package_type'] origin_hp = request_data['origin_handover_point'] destination_hp = request_data['destination_handover_point'] #some calculation return JsonResponse({'_price':25000}) #just an example Here is my urls.py in project from django.contrib import admin from django.urls import path, include from rest_framework import … -
Django test | DETAIL: Key (id)=(1) is still referenced from table "validation_loyaltydocumentvalidation"
I work on Python 3.7 and the project migrated recently from Django 1.11 to Django 2.0.9. When i run ./manage.py test I encounter the following error : django.db.utils.IntegrityError: update or delete on table "pizzeria_loyaltydocument" violates foreign key constraint "validation_docum_document1_id_94a0a84b_fk_pizzeria" on table "validation_loyaltydocumentvalidation" DETAIL: Key (id)=(1) is still referenced from table "validation_loyaltydocumentvalidation". It seems that issue come from my test setUp() : class PizzaTestCase(TestCase): def setUp(self): self.customer, self.record, self.best_pizza = create_pizzeria_context() # here documents are created using LoyaltyDocument.objects.create() create_loyalty_documents(self.customer) LoyaltyDocument.objects.filter( customer=self.customer, kind='loyalty' ).delete() self.loyalty_document = ProfileDocument.objects.create( customer=self.customer, kind='loyalty' ) def create_loyalty_documents(customer): loyalty_document = ProfileDocument.objects.create( kind="loyalty", customer=customer, ... As mentioned in the comment, a loyalty document with id = 1 is already created within create_loyalty_documents() and if a comment out that part i get no such error but most of my tests fails as i need that document deleted. Why such error appears as it was not the case while on Django 1.11 ? What am I doing wrong / How to overcome that error ? Thanks -
I want to remove some characters from a string in js
I am making an Website with Django (Python Framework). I am passing string like this : Products you ordered: {"pr7":[4,"Mi Phone 8 GB RAM, 128GB ROM",7000],"pr8":[5,"Usha Mixer Grinder (White)",1244],"pr9":[4,"iBall 10000 MAh power bank (Black)",1455]} from my models.py to views.py to my html template but I don't want to my string to be like this my string is : Products you ordered: {"pr7":[4,"Mi Phone 8 GB RAM, 128GB ROM",7000],"pr8":[5,"Usha Mixer Grinder (White)",1244],"pr9":[4,"iBall 10000 MAh power bank (Black)",1455]} I want my string to be like : Products you ordered: Mi Phone 8 GB RAM 128GB ROM,Usha Mixer Grinder (White),iBall 10000 Mah power bank (Black) -
Django query: Order by the number of the overlapped elements of array with a list variable
I have an ArrayField in my postgresql db table. I would like to order my queryset by the number of the overlapped elements with a fixed list variable. I couldn't find a solution using ORM. Then I apply this raw query stated in https://stackoverflow.com/a/51612751: SELECT i.food_list, x.ct FROM main_recipes i , LATERAL ( SELECT count(*) AS ct FROM unnest(i.food_list) uid WHERE uid = ANY('{water,banana}') ) x ORDER BY x.ct desc; The problem now is that I cannot include this solution to my queryset in ORM: qset = Recipes.objects.annotate(val=RawSQL(""" SELECT x.ct FROM main_recipes i , LATERAL ( SELECT count(*) AS ct FROM unnest(i.food_list) uid WHERE uid = ANY(%s) ) x """, (includeList,))).order_by('val') This gives the error: django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression I much appreciate your any kind of solution ORM or row. -
Django how to get db_column from object_list.values()
I have the following model. class TSample(models.Model): foo1_id = models.DecimalField(max_digits=8, decimal_places=2, db_column='foo1_id__c') foo2_f = models.DateTimeField(null=True) I have used a paginator and read data inside a loop as follows. query = self.model.objects.filter(...).order_by('updated_at') paginator = Paginator(query, self.batch_size) for i in paginator: data = list(i.object_list.values()) encoded_data = json.loads(json.dumps(data, cls=DjangoJSONEncoder)) print(encoded_data) The data I get does not have the db_column I have mentioned in the model. Instead the field name in the model. [{'foo1_id': 1.2, 'foo2_f': '2020-12-07T07:31:25Z'}] Expected data is, [{'foo1_id__c': 1.2, 'foo2_f': '2020-12-07T07:31:25Z'}] How can I get the expected result with the db_column name -
MultiValueDictKeyError in Django Project
View.py if req.method == 'POST': df = DocumentForm.objects.filter(document_id=id) logging.info('LOG: I am here') if df.exists(): for d in df: description = req.POST['{}'.format(d.description, False)] displayName = req.POST['{}'.format(d.displayName, False)] df.update(displayName=displayName, description=description) return redirect('/adboard/upd') HTML File <form class="needs-validation" action="{{id}}" method="POST" enctype="multipart/form-data" novalidate> {% csrf_token %} <div class="row mt-3 mb-3"></div> {% if messages %} <div class="alert alert-danger" role="alert"> {% for message in messages %} {{ message }} {% endfor %} </div> {% endif %} {% for df in data %} <div class="form-group"> <small class="text-muted bold-label m-lower">&#123;{{df.field}}&#125;</small> <label for="validationCustom01">{{df.displayName}}</label> <input type="text" class="form-control" id="validationCustom01" name="{{df.displayName}}" value="{{df.displayName}}" placeholder="Enter Display Name"> <label for="validationCustom01">{{df.description}}</label> <input type="text" class="form-control" id="validationCustom01" name="{{df.description}}" value="{{df.description}}" placeholder="Enter description"> <div class="invalid-feedback"> Please enter required fileds. </div> <!-- <div class="valid-feedback"> Looks good! </div> --> </div> {% endfor %} <button type="submit" class="btn btn-primary btn-red btn-block">SAVE</button> </form> What I am trying to achieve is. Pass a variable form to the user to fill And I get the result. I can't tell what the input id/name would be because it's a variable. But I am finding it difficult getting the value from the view.py file. -
Fill Many to Many field through API
I am trying to implement an API to add Agent. The Agent has Many To Many field, Role. I am using Django and Django Rest Framework. Here is the models : class Role(models.Model): code = models.CharField(max_length=50, primary_key=True) labe = models.CharField(max_length=50) def __str__(self): return '%s %s' % (self.labe, self.code) class Agent(models.Model): firstName = models.CharField(max_length=60) lastName = models.CharField(max_length=60) role = models.ManyToManyField(Role) So I created Serializers : class RegistrationSerializer(serializers.ModelSerializer): class Meta: model = Agent fields = ['email', 'firstName', 'lastName', 'role', 'phoneNumber', 'experienceWorkYeares'], role = serializers.PrimaryKeyRelatedField( many=True, read_only=True) extra_kwargs = { 'password': {'write_only': True}, } def save(self): agent = Agent.objects.create( email=self.validated_data['email'], firstName=self.validated_data['firstName'], lastName=self.validated_data['lastName'], phoneNumber=self.validated_data['phoneNumber'], experienceWorkYeares=self.validated_data['experienceWorkYeares'] role=self.validated_data['role'] // One of my multiple try but doesn`t work. ) agent.save() return agent How can I retrieve the role I sent via Postman and put it in the agent ? for the role I am POSTing role = "CODE1". Thank you so much in advance. Basically what I am trying to do is : For each Agent there one or more role. I trying a lot of thing and I follow documentation but I am not able to do it. -
Scheduler for Django 3.0
I'm in a project where we must schedule some tasks. Most of the time, we just need to launch in background some treatment to end a potentially long http request. We schedule a job that will take some times (but that need to be executed once). We're using Django (version 3.0) and we're using Azure ecosystem for the database/etc. We need a scheduler that: Can schedule jobs to be run asap (these jobs need to access database and django functionalities). Can manage concurency between django application : most likely, our application will be running on multiples workers (Azure web app). Can use database to store results. Can manage retry/failure/etc. I have used django-scheduler, but it doesnt manage concurency well. I have seen about celery but I'm not sure about the usage in these conditions. What are your advices ? Thanks -
Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<post_id>[0-9]+)/share/$']
show_more.html <p> <a href="{% url 'mains:post_share' post_id %}">Share This Post</a> </p> urls.py path('<int:post_id>/share/',views.post_share,name='post_share'), views.py def post_share(request, post_id): post = get_object_or_404(Post,pk=post_id, status='published') if request.method == 'POST': form = EmailPost(request.POST) if form.is_valid(): else: form = EmailPost() return render(request, 'mains/post_share.html', {'post':post,'form':form}) forms.py class EmailPost(forms.Form): name_subject = forms.CharField(max_length=400) email = forms.EmailField() description = forms.CharField(required=False,widget=forms.Textarea) Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<post_id>[0-9]+)/share/$']. This error is raising when i click on share the Post. Please help me to solve this Error. I will really appreciate your Help. -
how to access second models field of join operation in django templates
I'm doing a join operation Django. these are two models: in the users app: class User(AbstractBaseUser, PermissionsMixin): ... company = models.CharField(_('company'), default='', max_length=50, null=True, blank=True) ... in contacts app: class Contact(models.Model): owner = models.OneToOneField( User,null=True, blank=True, on_delete=models.CASCADE) ... in my views.py I'm doing a join operation like the following to get contacts distincted by sender_id and I want the company name of the sender. user_contacts = Contact.objects.distinct('sender_id').select_related() in my template I can access the contacts field like {{contact.sender_name}} but how to access the users field? this is my query: print(user_contacts.query) SELECT DISTINCT ON ("contacts_contact"."sender_id") "contacts_contact"."id", "contacts_contact"."owner_id", "contacts_contact"."sender_id", "contacts_contact"."sender_name", "contacts_contact"."chat_id", "contacts_contact"."receiver_id", "contacts_contact"."subject", "contacts_contact"."message", "contacts_contact"."myfile", "contacts_contact"."contact_date", "contacts_contact"."user_id", "contacts_contact"."is_answered", "contacts_contact"."message_id", "contacts_contact"."status", "users_user"."id", "users_user"."password", "users_user"."last_login", "users_user"."is_superuser", "users_user"."first_name", "users_user"."last_name", "users_user"."date_joined", "users_user"."is_active", "users_user"."is_staff", "users_user"."company", "users_user"."address", "users_user"."zipcode", "users_user"."city", "users_user"."country", "users_user"."tel", "users_user"."mobile", "users_user"."fax", "users_user"."email", "users_user"."user_id", "users_user"."title", "users_user"."website", "users_user"."avatar" FROM "contacts_contact" LEFT OUTER JOIN "users_user" ON ("contacts_contact"."owner_id" = "users_user"."id")