Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can ı use same url in Django
I want to user same url but in different view, how can ı do this? here my urls url(r'^(?P<slug>\S+)/$', QuestionDetailView.as_view(), name='detail'), url(r'^(?P<slug>\S+)/$', QuestionUniListView.as_view(), name='uni-list'), this slugs get different models. When ı run like this only one url works? -
Django Admin Filter by one to many relationship
I'm wanting to create a filter so that I can see whether or not a (reverse foreign key?? field is null or not). Eg: Class Order:(orderId) Class OrderLineItem:(orderLineItemId, productId, date, orderForeignKey, embroidery_name) On the list view page of Order I want to be able to filter orders by whether or not the order's line items have an embroidery_name or not... -
django cache still expires after 15 minutes even after setting timeout
In Django version 2.0.3 settings.py I set cache as CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'TIMEOUT': 20, } } And I ran memcached as memcached -vv But it still takes 15 min for cache to expire. -
How do I pass data from a view to a custom mixin in Django?
Two of my views share a substantial amount of code, which makes it hard to maintain. For that reason I decided to move the common code into a custom mixin. A simplistic example: class StatisticsMixin(object): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user_products = Product.objects.filter(user=self.request.user).select_related() context["total_products"] = user_products.count() context["total_products_open"] = user_products.total_new() return context Now, my views would look like this: class DashboardView(LoginRequiredMixin, StatisticsMixin, TemplateView): model = Product template_name = "products/dashboard.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user_products = Product.objects.filter(user=self.request.user).select_related() # Some other code return context class AnalyticsView(LoginRequiredMixin, StatisticsMixin, TemplateView): model = Product template_name = "products/analytics.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user_products = Product.objects.filter(user=self.request.user).select_related() # Some other code return context The issue is the following in the custom mixin, StatisticsMixin: user_products = Product.objects.filter(user=self.request.user).select_related() which in different views could be something else. So, I am trying to find a way for the custom mixin, to get the data from the view and not be hardcoded in it. -
Django serializers: why does self.fields.pop('field_name') work?
Referring to the following link as an example (and plenty of other examples exist elsewhere): http://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields It's understood that Django serializer fields are defined typically using a tuple, which is immutable: class UserSerializer(DynamicFieldsModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') However, the accepted way to dynamically change serializer fields involves using a pop (self.fields.pop(field_name)) class DynamicFieldsModelSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) How do fields get defined? Is there a pre-processing step in Django serializers? -
Api to return current user and photo from Django
I'm trying to create an api call that will return the username of the individual that logged in as well as their photo. I am logging in via an app and attempting to fire off that api call when the user logs in. I am using the rest_framework_simplejwt to sign in and assign a token then return that token via the app to use to access data in various api calls. Right now This what I have so far: URL: url(r'^api/token/$', TokenObtainPairView.as_view()), Api Call: @csrf_exempt def current_user(request): if request.method == 'POST': driver = JWTAuthentication().authenticate(request)[0].driver driverInfo = request.user.get_full_name() return JsonResponse({"success": driverInfo}) Right now it -
URL regex that will match /x/y but also just /x
I'm following a tutorial, and am getting an 404 error that http://127.0.0.1:8000/restaurants/ is not being matched by url(r'^restaurants/(?P<slug>\w+)/$', RestaurantListView.as_view()) while http://127.0.0.1:8000/restaurants/x with any x is. How should I rewrite the path to match the url without any additional /x? ... Error message: Using the URLconf defined in projekt.urls, Django tried these URL patterns, in this order: admin/ ^contact/$ ^$ ^about/$ ^restaurants/(?P<slug>\w+)/$ The current path, restaurants/, didn't match any of these. -
What caching backends can be implemented in django
Which of the caching strategies can be implemented in django? What are the pros and cons of each cache backends (in terms of ease of use and ease of developing)? Which backend should be preferred for production etc. -
Django choices vs store in data base
What is better to do in case you want to set fixed choices in a model, but they are too numerous? I will put an example with countries, is not exactly my case, but is with geographic locations: This: COUNTRY_CHOICES = ( ('A', 'ARGENTINA'), # 200 more countries ) # model field my_field = models.CharField( choices = COUNTRY_CHOICES ) Vs store every value in database. Thanks. -
Best practice for storing user API keys?
the app I'm working on requires users to provide their API key's to a third party service so that the app can pull the users data from the third party and process it. What is the best practice for storing each users unique keys? I've seen people talk about storing it into the user model as a field or setting up a separate file that get's imported where needed. -
AttributeError at / 'str' object has no attribute 'objects'
I am new to Django. I am working on a project that uses weather API to get the weather.Everything was working fine until models.py was made and imported city on views.py I use ver. 1.11.13 models.py from __future__ import unicode_literals from django.db import models class city(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Meta: verbose_name_plural ='cities' views.py ( Error comes at cities = city.objects.all()) import requests from django.shortcuts import render from .models import city def index(request): url= 'http://api.openweathermap.org/data/2.5/weather?q={}& units=imperial&appid=e1a2ef38103d2e572d316e38452e2acd' city = 'Lucknow' cities = city.objects.all() weather_data =[] for city in cities: r= requests.get(url.format(city)).json() city_weather = { 'city':city.name , 'temperature' :r['main']['temp'], 'description' :r['weather'][0]['description'], 'icon' :r['weather'][0]['icon'] , } weather_data.append(city_weather) print(weather_data) context = {'weather_data' : city_weather} return render(request,'weather/weather.html', context) -
Django DRF: POST to CreateAPIView with list of PrimaryKeyRelatedFields
I have a many-to-one relationship between the following models class Story(models.Model): id = models.CharField(max_length=12, primary_key=True) class Article(models.Model): id = models.CharField(max_length=16, primary_key=True) title = models.CharField(max_length=500) address = models.URLField() story = models.ForeignKey(to=Story, blank=True, null=True, on_delete=models.CASCADE) Suppose I post several article objects to the database successfully. I identify that the articles with the ids ['1', '2', '3'] are all reporting on a particular Story. I want create a Story via a POST method to a CreateAPIView view like this POST http://127.0.0.1/news/story {articles': ['1', '2', '3']} Here is my serializer class StorySerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() articles = serializers.PrimaryKeyRelatedField(many=True, allow_empty=False, queryset=Article.objects.all()) class Meta: model = Story fields = ('id', 'articles') Here is my view class StoryList(generics.ListCreateAPIView): serializer_class = StorySerializer query_set = Story.objects.all() I want to ensure that 1) the articles exist. 2) the article story is updated before the Story object is created. Suppose I run this as it is, I will get the following error: Got a TypeError when calling Story.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Story.objects.create(). You may need to make the field read-only, or override the StorySerializer.create() method to handle this correctly. So here is an attempt … -
Django, Haystack, Elasticsearch: Search comes up empty
Setting: I have a sqlite3 db populated with 119 files that contain, identifier, title, speaker and transcribed text. I would like to make that text searchable on a Django site, using Haystack and Elasticsearch. I have mainly followed this guide. Problem: My http://127.0.0.1:8000/search/ site looks fine, but when I search something, e.g. "africa" or "artificial intelligence" I get no results (see screenshot below). The Elastic search server is running fine, and doing queries in a notebook such as res = es.search(index="transcription-index", body={"query": {"match": {"trans":"africa, music"}}}) for hit in res['hits']['hits']: print("***********************") print('Title:', hit['_source']['title']) print("***********************") print('Speaker:', hit['_source']['speaker']) print("***********************") print('Description:', hit['_source']['description']) print("***********************") print(hit['_source']['trans']) print("***********************") print(hit['_score']) print("***********************") return meaningful results, just like I want it. Code: models.py from django.db import models from .search import transcription_index class transcription(models.Model): identifyer = models.CharField(max_length=20, default='') title = models.CharField(max_length=200, default='') speaker = models.CharField(max_length=50, default='') description = models.CharField(max_length=1000, default='') trans = models.CharField(max_length=30000, default='') # Method for indexing the model def indexing(self): obj = transcription_index( identifyer=self.identifyer, speaker=self.speaker, title=self.title, description=self.description, trans=self.trans ) obj.save() return obj.to_dict(include_meta=True) def save(self, *args, **kwargs): return super(transcription, self).save(*args, **kwargs) def __unicode__(self): return "{}:{}".format( self.identifyer, self.title, self.speaker, self.description, self.trans) search_indexes.py from haystack import indexes from elasticsearchapp.models import transcription class transcription_index(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField( document=True, use_template=True) identifyer = indexes.CharField(model_attr='identifyer') … -
Django fileField works on admin page, but not on form
So I'm trying to make a form with a fileField in Django, and it works correct if I access it in the admin page, however when I use in my form it's not valid. request.FILES returns <MultiValueDict: {}> However the file shows up in request.body at the end 'csrfmiddlewaretoken=71Bg3CNHChPrGuOJlVTPJuvX7RsU6o3DiOMtZnPciNwLAubF1ThfgOLM7htaBvba&userName=daniel&infoName=a&linkURL=http%3A%2F%2Fa.com&fileField=IMG_20180608_145044.jpg&addInfo=' The form works perfectly fine if I remove the fileField. I've read about the need for the enctype, but my form still refuses to work. class AdditionalInfoForm(forms.Form): userName = forms.CharField(widget = forms.TextInput(attrs={'class': 'form-control typeahead-basic', 'placeholder': ''})) infoName = forms.CharField(widget = forms.TextInput(attrs={'class': 'form-control'})) linkURL = forms.CharField(widget = forms.TextInput(attrs={'class': 'form-control', 'type': 'url'})) fileField = forms.FileField(widget = forms.FileInput(attrs={'action': '', 'method': 'post', 'data-ajax': 'false', 'class': 'form-control', 'enctype': 'multipart/form-data', 'input type': 'file'})) And the important part in the template would be this <div class="form-group"> <label class="control-label col-lg-3">Upload File</label> <div class="col-lg-9"> {{ additionalInfoForm.fileField }} </div> </div> -
How can I add a csv file into Django models
I have a csv file which has contents like the following: stores.csv Site, Score, Rank roolee.com,100,125225 piperandscoot.com,29.3,222166 calledtosurf.com,23.8,361542 cladandcloth.com,17.9,208670 neeseesdresses.com,9.6,251016 ... Here's my model. models.py class SimilarStore(models.Model): store = models.ForeignKey(Store) csv = FileField() domain = models.CharField(max_length=100, blank=True) score = models.IntegerField(blank=True) rank = models.IntegerField(blank=True) So, I wanna upload the stores.csv file into csv field so that each column data goes into each domain, score, and rank. I found out some resources making python file to parse data and run it through a command like `python parse.py'. However, I need it to be done by uploading the csv file in Django admin. Can anyone explain how I can do that? -
CORS header not working for Django backend- Angular frontend
I implemented CORS on my Django backend by installing django-cors-headers and following the steps mentioned in- https://github.com/OttoYiu/django-cors-headers. Essentially, I performed the following steps- pip install django-cors-headers INSTALLED_APPS = ( ... 'corsheaders', ... ) MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ORIGIN_WHITELIST = ( 'localhost:8000', //LB '10.254.138.226:443' ) I still can not make it work when I use my angular front-end. For example, my POST request becomes OPTIONS. zone.js:2935 OPTIONS https://10.254.138.226/api/users 0 () error is ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …} I don't have this problem when I use postman. Could someone help? -
host-specific request breaks unrelated test cases
I have the following tests: from django.test import TestCase from django.core.urlresolvers import reverse class TestA(TestCase): def test_a(self): reverse('view1') class TestB(TestCase): def test_b(self): self.client.get('/view2/', HTTP_HOST='second.test.net') class TestC(TestCase): def test_c(self): reverse('view1') TestA and TestB run successfully, but TestC breaks with ..E ====================================================================== ERROR: test_c (dhtest.tests.test_view2.TestC) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/phihag/dhtest/dhtest/tests/test_view2.py", line 14, in test_c reverse('view1') File "/home/phihag/.local/share/virtualenvs/dhtest---IwXRQ3/lib/python3.6/site-packages/django/urls/base.py", line 91, in reverse return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/home/phihag/.local/share/virtualenvs/dhtest---IwXRQ3/lib/python3.6/site-packages/django/urls/resolvers.py", line 497, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'view1' not found. 'view1' is not a valid view function or pattern name. ---------------------------------------------------------------------- Ran 3 tests in 0.006s FAILED (errors=1) But when I comment out TestB, TestC works! How do I fix this problem? I'm using django-hosts with the following configuration: from django.conf import settings from django_hosts import patterns, host host_patterns = patterns( '', host( r'second\.test\.net', 'dhtest.secondurls', name='second' ), host( r'(\w+)', 'dhtest.urls', name='default' ), ) and fairly simple URL files: # dhtest/urls.py from django.conf.urls import url from django.http import HttpResponse urlpatterns = [ url(r'^view1/', lambda _: HttpResponse('This is view1'), name='view1'), ] # dhtest/secondurls.py from django.conf.urls import url from django.http import HttpResponse urlpatterns = [ url(r'^view2/', lambda _: HttpResponse('view2 on another host')), ] For reference, here is the full project. -
Django modelForm is not saving file to DB
Django 2.0 Python 3.6 I am having trouble with a Django form that is not saving the file that is selected through the form; whenever you select a file to upload, I receive the message "This Field is Required.". I placed a blank=True and a null=True in the Model FileField to get rid of the same, but whenever I attempt to load the html, I get this error: "The 'copydoc' attirbute has no file associated with it." I would like for a user to be able to log in, create an entry and upload a file along with said entry. Why doesn't the DB accept the file from the form? Thank you. views.py: from django.shortcuts import render, redirect from .models import notarizer, CustomUser, notarizerCreateForm # from .forms import notarizerCreateForm # Create your views here. def home(request): t = 'home.html' return render(request, t) def page1(request): t = 'log1/page1.html' if request.user.is_authenticated: logger = notarizer.objects.filter(userziptie=request.user).order_by('-date') return render(request, t, {'logger': logger}) else: return redirect(home) def create_entry(request): createPath = 'log1/create_entry.html' if request.method == 'POST': if request.method == 'FILES': form = notarizerCreateForm(request.POST, request.FILES) if form.is_valid(): instance =notarizerCreateForm( file_field=request.FILES['file'] ) instance.save() else: print(form.errors) else: form = notarizerCreateForm(request.POST) if form.is_valid(): form.save() else: print(form.errors) else: form = notarizerCreateForm() return … -
Django + Celery: ImportError: No module named project.urls
When I start a worker using Django and Celery using this command (I execute the command within the d directory): celery -A e.project.celery:app worker -l info File "/Users/.../..../e/venv/lib/python2.7/site-packages/celery-4.2.0-py2.7.egg/celery/loaders/base.py", line 108, in import_default_modules raise response ImportError: No module named project.urls I am using Django 1.11 and Celery 4.2 with Python 2.7. Below is my project structure with the contents of some files that should be helpful for debugging. Django structure: d/ __init__.py e/ __init__.py core/ __init__.py app1/ __init__.py tasks.py project/ (project stuff) __init__.py celery.py settings.py urls.py context_processors.py wsgi.py manage.py setup.py settings.py: INSTALLED_APPS = [ '...', 'django_celery_results', 'django_celery_beat' ] CELERY_RESULT_BACKEND = 'django-db' CELERY_BROKER_URL = 'redis://foo:foo@127.0.0.1:6599/1' CELERY_CELERYBEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' e/project/__init__.py: from __future__ import absolute_import, unicode_literals from e.project.celery import app as celery_app __all__ = ('celery_app', ) e/project/celery.py: from __future__ import absolute_import, unicode_literals import os import sys from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "e.project.settings") app = Celery('e_tasks') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() if __name__ … -
How to connect a websockify/nvc instance to a Python Django application? (404 errors)
My question is how to integrate websockify and novnc. I have a novnc codebase recently integrated into a Django app. The codebase is here: https://github.com/novnc/noVNC Unfortunately I am limited in what I can share of my own code for IP and private repository reasons so please bear with me here. So far, I have a qcow2 file creating a virtual machine image, which I am able to access by running the following command from the command line: I am able to successfully negotiate a connection to my virtual machine. The following additional info is supplied when I look in the dev tools console. I have integrated this functionality, and the javascript, into a Django template, as well as the views and urls. I can now get the Django server to serve me my file, but I'm having a hard time figuring out how to change the novnc config to allow this console to connect to my virtual machine from the newly hooked up django page. When I do try that, I get this: I'm new to networking but here is my basic question. Django is running on localhost:8000. Websockify is proxying to novnc from port 6080 to port 5959. Is … -
WebSocket – Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID
after adding the SSL certificates, we are getting the following error in our chat: WebSocket connection to 'wss://ec2-XXXXXXX.us-east-2.compute.amazonaws.com:5002/ws/blablablabla/' failed: Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID We are using nginx, django and websockets. The chat is based on the following repository: https://github.com/Bearle/django-private-chat See here screenshot of the browser's log: https://drive.google.com/file/d/1S3WiUlALcNfYEKo3SENMmga9ktDUaNgb/view?usp=sharing Has anyone experienced anything similar? Please, let me know if you need more details of the set up. See below our nginx configuration listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/casista.com-0001/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/casista.com-0001/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot upstream chatserver { server ec2-13-58-129-240.us-east-2.compute.amazonaws.com:8765; } client_max_body_size 4G; access_log /var/log/nginx/casista-access.log; error_log /var/log/nginx/casista-error.log; location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://unix:/home/ubuntu/mywasi-root/mywasi/mywasi.sock; break; } # include proxy_params; location /ws { # proxy_pass http://ec2-13-58-129-240.us-east-2.compute.amazonaws.com:8765; proxy_pass http://chatserver; # proxy_pass http://localhost:8765; proxy_connect_timeout 7d; proxy_read_timeout 7d; proxy_send_timeout 7d; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } auth_basic "Restricted content"; auth_basic_user_file /etc/nginx/.htpasswd; } location /static/ { alias /home/ubuntu/mywasi-root/mywasi/staticfiles/; autoindex off; } location /media/ { alias /home/ubuntu/mywasi-root/mywasi/media/; autoindex off; } -
Different installations of Python on web server - NTLK installation issue
I am new to web development. I am having an issue importing nltk in Python when I access my shared web hosting account (Linux) with Putty. I have a shared hosting account and I have several domains. I have started trying to develop a couple of site using Django: let's call them Site1 and Site2. I have separate virtualenvs for Site1 and Site2. I have in the shared "base" directory an installation of Python3.6. I then have separate installations of Python in the virtualenv bin folders for site1 and site2. I am trying to install NLTK on Site1. I have done the following: (1) Accessed the server through Putty. (2) Run the virtualenv for Site1. (3) Typed 'pip install nltk'. - The package is saved to the /site1-virtualenv/lib/python3.6/site-packages directory. I presume the PIP command is linked to the Python installation for Site1. (4) To download the NLTK Data, I run the Python shell by typing 'python' in the Site1 virtualenv. When I type 'import nltk' in the python shell, I get error: Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'nltk' I think this is because the 'python' command is running the installation of … -
ValueError: badly formed hexadecimal UUID string while using Django model for UUIDField
I am using Django==1.9 , My models.py looks something as from __future__ import unicode_literals from django.db import models import uuid # Create your models here. class Status(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False) comment = models.CharField(max_length=1000, unique=True) When I run python manage.py migrate it throws me File "C:\Python27\Lib\uuid.py", line 136, in __init__ raise ValueError('badly formed hexadecimal UUID string') ValueError: badly formed hexadecimal UUID string Note that, The database table is not yet created in sqlite3.db so other answers for the similar looking question on Stack-Overflow suggests you should drop the database if exists and then migrate. But in my case the database doesn't exists as of now. I tried most of the Stack-Overflow answer, some suggest use default='' , some says default=uuid.uuid4() etc. Nothing works for me, that is the reason why I created a new question. So, please don't link to answer just by blindly looking at the title ! -
Positional argument 'request' for for method task
I have django views.py method like def index(request): .... return render(request, 'index.html') And it works well. Now i'm trying to set celery task to run like @shared_task def add(): views.index() But I get error in celery worker as TypeError: _wrapped_view() missing 1 required positional argument: 'request' I see I need to pass request as argument for index but I'm not sure what exactly I'm suppose to pass? -
Translating a SQL query to Django ORM with self joins
I want to grab a list of players with player's id and their player_attribute values (more than one) in a single response like {player_id: 1, first_value: 2, last_value: 3}, I can replicate this in Flask and peewee/sqlalchemy but can't figure it out with Django. I have a Query like this: SELECT DISTINCT p.player_id, fn.value, ln.value FROM player p INNER JOIN player_attributes fn ON fn.player_id=p.player_id AND fn.attribute_id=123 and fn.end_time is NULL INNER JOIN player_attributes ln ON ln.player_id=p.player_id AND ln.attribute_id=456 and ln.end_time is NULL WHERE p.player_type_id = 789 ORDER BY ln.value, fn.value With models: class PlayerAttributes(models.Model): player_attribute_id = models.AutoField(primary_key=True) value = models.CharField(max_length=255, blank=True, null=True) end_date = models.IntegerField(blank=True, null=True) player = models.ForeignKey( player, models.DO_NOTHING, related_name="player_attributes" ) attribute = models.ForeignKey( Attribute, models.DO_NOTHING, related_name="player_attributes" ) class Player(models.Model): player_id = models.AutoField(primary_key=True) class Attribute(models.Model): attribute_id = models.AutoField(primary_key=True) I tried to prefetch it with a QuerySet (?) and did not get my JOINs in the resulted query when I printed q.query. This is my current code: first_attribute = PlayerAttributes.objects.filter( end_time=None, attribute=123 ) last_attribute = PlayerAttributes.objects.filter( end_time=None, attribute=456 ) players = ( Player .objects .filter( player_type=789 ) .prefetch_related( Prefetch( "player_attributes", queryset=first_attribute, to_attr="first_attribute" ) ) .prefetch_related( Prefetch( "player_attributes", queryset=last_attribute, to_attr="last_attribute" ) ) .values("player_id", "first_attribute__value", "last_attribute__value") ) return players I tried …