Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django HttpResponseRedirect either crashes the site or shows a blank page
I have this issues with Django forms where on each refresh the form would resubmit the last input into the database I tried working with "HttpResponseRedirect" but it would either crash the site or show a blank page. Heres the code of views.py def page(request) : employe = Employe.objects.all() if request.method =='POST' : form = EmployeForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect("") else : form = EmployeForm() return render(request,'hello.html',{'employe':employe,'form':form,}) -
How can I display users in the chat list?
In my project, when, for example, user1 asks for help, then user2 finds this request for help and writes to user1 to agree on further actions for help. My chat is registered in such a way that all users who can be written to are displayed on the left, namely, all registered users, and the chat itself is located to the right of this column. I would like the left column to display, for example, user2 (the one who helps) user1 (who is being helped) and those to whom he wrote earlier were displayed. Here is the chat code: html code: {% extends 'chat/base.html' %} {% load static %} {% block header %} <style> #user-list a.bg-dark { background-color: rgb(107, 107, 107) !important; } .list-group-item { cursor: pointer } .chat-bubble { min-width: 40%; max-width: 80%; padding: 5px 15px; } #user-list a:hover * { text-decoration: unset; } .chat-box { overflow: auto; max-width: 100%; } </style> {% endblock %} {% block content %} <div class="container" style="height: 75%;"> <div class="card bg-dark h-100 border-light"> <div class="card-body h-100"> <div class="row h-100"> <div class="col-md-4 border-right h-100"> <div class="list-group bg-dark" id='user-list'> {% for u in users %} {% if not u.id == 1 and not u.id == user.id … -
Django - Filterset without model
I have such http-request route: frontend > proxy (drf) service > data service (sap) The view in proxy service: def get_data_from_remote_api(): # this is mock return [ {'first_name': 'Brad', 'last_name': 'Pitt'}, {'first_name': 'Thomas', 'last_name': 'Cruise'}, {'first_name': 'Robert', 'last_name': 'Downey'}, ] class RemoteUsersView(ViewSet): # TODO: # define filtering class (data from query params) # with multiple fields (`first_name`, `last_name`) # so it is displayed in swagger def list(self, request): users = get_data_from_remote_api() # here need to filter return Response('list') def create(self, request): return Response('create') def retrieve(self, request, pk): return Response('retrieve') def update(self, request, pk): return Response('update') def destroy(self, request, pk): return Response('destroy') As you can see a list of dicts should be filtered. So I cannot use FilterSet because it needs Django model. How can I do that? -
Creating a Html Template with 2 search bars : How to not to loose get method values
I am displaying to different models as list on my Html template. I also want a search bar for both of these tables. If any search post was made on one of the tables I don't want it to overwritten when a new search post is made on the other table. This is what I have : views.py class DocAssignClassification(ListView): model = Documents template_name = 'documentassignation/docassign_classification.html' def get_context_data(self, *args, **kwargs): context = super(DocAssignClassification, self).get_context_data(*args, **kwargs) search_post1 = self.request.GET.get('search1') search_post2 = self.request.GET.get('search2') if search_post1: context['notassigned_list'] = Documents.objects.filter(Q(timestamp__icontains=search_post1) | Q(statut__icontains=search_post1) | Q(filenamebeforeindex__icontains=search_post1) | Q(timestamp__icontains=search_post1)) else: context['notassigned_list'] = Documents.objects.all() if search_post2: context['notassigned_list'] = Entity.objects.filter(Q(timestamp__icontains=search_post1) | Q(statut__icontains=search_post1) | Q(filenamebeforeindex__icontains=search_post1) | Q(timestamp__icontains=search_post1)) else: context['notassigned_list'] = Entity.objects.all() urls.py urlpatterns = [ path('docassignation/classification', DocAssignClassification.as_view(), name="docassign_classification"), ] docassign_classification.html {% comment %} -------------FIRST TABLE---------------------------------- {% endcomment %} <form class="d-flex" action="{% url 'docassign_classification' uuid_contrat uuid_group %}"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search1"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> <table class="table"> <thead> <tr> <th scope="col"></th> <th scope="col">ID</th> <th scope="col">PdfNameBeforeIndex</th> </tr> </thead> <tbody> <tr > {% for object in notassigned_list %} <td>{{object.id}}</td> <td>{{object.filenamebeforeindex}}</td> </tr> {% endfor %} </tbody> </table> {% comment %} -------------SECOND TABLE---------------------------------- {% endcomment %} <form class="d-flex" action="{% url 'docassign_classification' uuid_contrat uuid_group %}"> <input class="form-control mr-sm-2" type="search" placeholder="Search" … -
Django - getting Error Reverse for 'book' with arguments '(1,)' not found. 1 pattern(s) tried: ['<int:flight_id/book\\Z']
I am learning the Django framework. Today I was trying to retrieve a URL in HTML template by using <form action="{% url 'book' flight.id %}" method="post"> Also, I've got a function book. Here is the code: def book(request,flight_id): if request.method=="POST": flight=Flight.objects.get(pk=flight_id) passenger=Passenger.objects.get(pk=int(request.POST["passenger"])) passenger.flights.add(flight) return HttpResponseRedirect(reverse("flight",args=(flight.id,))) And this is the urls.py file : urlpatterns = [ path("",views.index,name="index"), path("<int:flight_id>",views.flight,name="flight"), path("<int:flight_id/book",views.book,name="book") ] But I don't know why it is showing an error: NoReverseMatch at /1 Reverse for 'book' with arguments '(1,)' not found. 1 pattern(s) tried: ['<int:flight_id/book\Z'] -
there are no errors in the models, but when I create a migration, this is displayed
(venv) PS C:\django-sites\testsite> python manage.py makemigrations System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace No changes detected (venv) PS C:\django-sites\testsite> my code: from django.db import models class News(models.Model): title = models.CharField(max_length=150) content = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') is_published = models.BooleanField(default=True) #id - INT #title - Varchar #content - Text #createrd_at - DateTime #updated_at - DateTime #photo - Image #is_published - Boolean -
How to create a relations between primary key and foreign key in Django models and POST values into DB
I have a Django app which is basically an Online shopping. Right now I have two models: User_details and Extend_user_deatils. In User_details I have(Username, Firstname, lastname, email, etc..). Now after that i need to extend User_details Model with Other Fields so I have Created another Model Extend_user_deatils consisting of (Mobile , Age) columns. Now i need to Link those Two Models, for that I have written an logic with Foreign Key Reference class User_details(models.Model): #Table 1 id = models.AutoField(primary_key=True, db_column='user_id') username = models.CharField(max_length=50) first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.CharField(max_length=50) class Extend_user_details(models.Model): #Table 2 user =models.ForeignKey(User_details, on_delete=models.CASCADE,db_column='user_id') mobile = models.BigIntegerField(blank=True, null=True) age = models.IntegerField(blank=True, null=True) When I Open Django admin Page and Post the Data it is Working Fine and Values are posting into DB. When I register as a User from register page . ForeignKey Column(user) from Table2 is showing Null .apart from that all the inputs is posting into DB as shown Screenshot Is there any way to solve this issue Thanks in Advance -
Django indexing the variable
Simple problem, big headache. html: {% for file in files %} {{ file.image }} {% endfor %} output: pdf/filename.jpg What I need: filename.jpg What I tried: {% for file in files %} {{ file.image[XYZ:XYZ] }} {% endfor %} -
How to find Locations inside some range to a particular lat long. python
I am doing a project in flutter and i need to display only the events that are happening in the nearest locations. suppose my location is of latitude 11.2588 and longitude 75.7804. then i need to find events inside latitude 11.2588 +/- 2 and longitude 75.7804 +/-2. I need the backend python service for this. service for finding events occurring inside 2 days is as follows: I want code for finding events in the nearest locations merged inside this. class uview(APIView): def get(self, request): now = dt.now() + timedelta(days=2) d = now.strftime("%Y-%m-%d") ob = Events.objects.filter(date__lte=d) ser = android_serialiser(ob, many=True) return Response(ser.data) def post(self, request): now = dt.now() + timedelta(days=2) d = now.strftime("%Y-%m-%d") ob = Events.objects.filter(e_id=request.data['eid'],user_id=request.data['uid'],date__lte=d) ser = android_serialiser(ob, many=True) return Response(ser.data) any help would be greatly appreciated. Thanks in advance :) -
Django CBV filter corresponding data
I have this view class Dashboard (LoginRequiredMixin, ListView): model = SchulverzeichnisTabelle template_name = 'SCHUK/Dashboard.html' context_object_name = 'Dashboard' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['User'] = User.objects.all() context['Schulverzeichnis'] = SchulverzeichnisTabelle.objects.all() context['BedarfsBerechnung'] = Bedarfs_und_BesetzungsberechnungTabelle.objects.all() context['JahrgangGebunden'] = JahrgangsgebundenTabelle.objects.all() context['JahrgangUebergreifend'] = JahrgangsuebergreifendTabelle.objects.all() context['FoerderBedarf'] = FoerderbedarfschuelerTabelle.objects.all() context['VorbereitungsKlassen'] = VorbereitungsklassenTabelle.objects.all() context['EinzelIntergration'] = EinzelintegrationTabelle.objects.all() context['SonderPaedagogen'] = SonderpaedagogenbedarfTabelle.objects.all() context['Lehrer'] = LehrerTabelle.objects.all() context['GL_Lehrer'] = GL_LehrerTabelle.objects.all() return context I have 2 groups one for Admins and the other for User. And I want as an Admin see all data that a user has made in the template, and also make it editable. The goal is to have User views where User is allowed to edit his data While the Admins can look it up on the Dashboard and also edit it or create something for the User User data reders fine and everything is good Admin does it too if I use objects.all but in that case it shows everything after eacher other like school 1 school 2 school 3 class 1 class 2 class 3 teacher 1 teacher 2 teacher 3 and I want to bundle it like school 1 class 1 teacher 1 and so on -
hi..i'm trying to create website but it gives me this error
from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('Eshop.urls')) ]+static(settings.MEDIA.URL, document_root=settings.MEDIA_ROOT) this code gives me this ]+static(settings.MEDIA.URL, document_root=settings.MEDIA_ROOT) AttributeError: 'str' object has no attribute 'URL's error: how can i solve it -
How to send socket data from Django website?
I have a simple website with a button on it and I would like to connect that button to a websocket and send arbitrary data to the socket once it is pressed. I need to calculate the time it takes for the signal to be sent and received once the button is pressed. html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Increment</title> </head> <body> {% block content %} Increment Counter <form id="form" method="post" action="#"> {% csrf_token %} <button type="submit", name="increment", value="increment">Increment</button> </form> <script type="text/javascript"> let url = `ws://${window.location.host}/ws/socket-server/` const chatSocket = new WebSocket(url) chatSocket.onmessage = function(e){ let data = JSON.parse(e.data) console.log('Data:', data) } </script> {% endblock %} </body> </html> I am very inexperienced so I am unsure how to do this. Any help would be appreciated. -
adding a user to a group on djngo admin and accessing it via views
if I add a user to a group on Django admin and assign permissions to the group, can I reference that user and its permissions in the views of my project? if yes how do I do it? thanks -
How do I use React with Django?
I have a Django project that currently run with a html template and vanilla js. If I want to shift the frontend to ReactJs. Is it possible to do so with minimal code changes in the backend? How big a change to the backend should I expect? -
no account logout Django Two factor auth
i am trying to implement two factor auth in my Django app. However, the user can bypass it by using the login provided by django.contrib.auth. is there any way i can redirect the user to /account/login when they browse for /login? Things i tried and have not work: removing django.contrib.auth (need this to logout) redundant login urls -
Django, model non-non-persistence field is None
In my model, I have a non-persistence field called 'client_secret'. The client_hash field is used in the custom model save method to calculate the hash. It worked as expected, but when I tried to save a new instance, self.client_secret is still None, why? class Client(models.Model): client_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) active = models.BooleanField(default=False) client_hash = models.BinaryField(editable=False, blank=True, null=True) # non-persistent field used to cal the hash client_secret = None def save(self, *args, **kwargs): if self._state.adding: self.client_hash = make_hash(self.client_secret) Trying to save a new client, client_secret is None in model save: Client.objects.create(active=True, client_secret='test_secret') -
how to fetch image from backend
import React from 'react' import { NavLink } from 'react-router-dom'; import * as ReactBootStrap from 'react-bootstrap' import "../Assets/styles/Supplier.css" import "../Assets/styles/button.css" import axios from "axios"; import { useEffect, useState } from 'react' const Supplier = () => { const [supplier, setSupplier] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState(false) // fetch data from the localhost and save it to the state useEffect(() => { setLoading(true) axios.get('http://127.0.0.1:8000/staff/supplier/') .then(res => { console.log(res.data) setSupplier(res.data) setLoading(false) }) .catch(err => { console.log(err) setError(true) }) }, []) return ( <> <body className="Body"> <section class="supplier_listing_whole"> <h1>Supplier listing</h1> <div class="supplier_listing"> <div className='button'> <NavLink to='/Supplier/SupplierForm' className={({ isActive }) => (isActive ? 'button-12' : 'button-12')}>registration</NavLink> </div> <ReactBootStrap.Table striped bordered hover> <thead> <tr> <th>id</th> <th>photo</th> <th>name</th> <th>email</th> <th>phone number</th> <th>birthdate</th> <th>identification card</th> </tr> </thead> <tbody> {supplier.map((supplier) => { return ( <tr key={supplier.id}> <td>{supplier.id}</td> <td> <img src={supplier.profile_picture} alt="image" class="picture" /> </td> <td>{supplier.user.first_name} {supplier.user.last_name}</td> <td>{supplier.user.email}</td> <td>{supplier.user.phone}</td> <td>{supplier.birthdate}</td> <td><img src={supplier.identification_card} alt={supplier.user.first_name} class="picture" /></td> </tr> ) })} </tbody> </ReactBootStrap.Table> </div> </section> </body> </> ) } export default Supplier; **i'm building a react js application and I'm finding a few thing a bit difficult since i'm relatively new to coding it self. For this instance i'm trying to fetch from Django API to … -
How to use order_by with last_added manytomanyfield?
Models.py class ChatRoomId(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_date = models.DateTimeField(auto_now_add=True) class MessageContent(models.Model): content = models.TextField(blank=True) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class PersonalMessage(models.Model): message = models.ForeignKey(MessageContent, on_delete=models.CASCADE) sender = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING) class PersonalRoom(models.Model): room_id = models.ForeignKey(ChatRoomId, on_delete=models.CASCADE) user = models.ManyToManyField(CustomUser) message_list = models.ManyToManyField(PersonalMessage) modified_date = models.DateTimeField(auto_now=True) How to order this queryset PersonalRoom.objects.all() by the value "message__created_date" ManyToManyField last added message_list object, which is last_item = message_list.all().order_by('-message__created_date')[0]. My idea is PersonalRoom.objects.all().order_by( Subquery( PersonalRoom.objects.get(pk=OuterRef('pk')).message_list.all().order_by('-message__created_date')[0] ) ) but this results in an error. -
I get a KeyError in request.data[] on put method in postman while code works?
I have an api coded in django rest framework. there is an update method and no problem when the data is updated from the local host. but i get KeyError='Person' when i try to call put method on postman in the code below. @action(methods=['put'], detail=True, url_path='personupdate') def personupdate(self, request, pk): transactionSaveId = transaction.savepoint() # person = self.get_object(self,pk) person = Person.objects.get(id=pk) getPersonData = {} getPersonData = request.data['Person'] if 'PictureType' in request.data['Person']: request.data['Person'].pop('PictureType') if 'JobStartDate' in request.data['Person']: request.data['Person'].pop('JobStartDate') if 'FormerSeniority' in request.data['Person']: request.data['Person'].pop('FormerSeniority') serializer = PersonCreateUpdateSerializer(person, data=getPersonData) the data is updated in db when i called from the localhost api. In the ggetPersonData = request.data['Person'] line i get this error from postman: KeyError: 'Person' I've tried everything from postman but I can't fix it -
Error starting django web application in cpanel using application manager
enter image description here emphasized text I am facing an error while deploying my django application on server using application manager in cpanel. image is being attached to it. Please help me any answer is welcome. thanks -
get cart total is not called...get_product logic was working before and still works but now why is it showing an error?
models.py\account class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) is_paid = models.BooleanField(default=False) def __str__(self): return str(self.user) def get_cart_total(self): cart_item = self.cart_item.all() price = [] for cart_item in cart_items: price.append(cart_item.product.discounted_price) if cart_item.color_variant: color_variant_price = cart_item.color_variant.price price.append(color_variant_price) if cart_item.size_variant: size_variant_price = cart_item.size_variant.price price.append(size_variant_price) print(price) return sum(price) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) color_variant = models.ForeignKey(ColorVariant, on_delete=models.SET_NULL, null=True, blank=True) size_variant = models.ForeignKey(SizeVariant, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.PositiveIntegerField(default=0) coupon = models.ForeignKey(Coupon, on_delete=models.SET_NULL, null=True, blank=True) def get_product_price(self): price = [self.product.discounted_price] if self.color_variant: color_variant_price = self.color_variant.price price.append(color_variant_price) if self.size_variant: size_variant_price = self.size_variant.price price.append(size_variant_price) return sum(price) views.py/shop def get_product(request,slug): try: product = Product.objects.get(slug=slug) context = {'product':product} if request.GET.get('size'): size = request.GET.get('size') price = product.get_product_price_by_size(size) context['selected_size'] = size context['updated_price'] = price print(price) return render(request, 'app/product-single.html',context = context ) except Exception as e: print(e) Product matching query does not exist. Internal Server Error: /favicon.ico/ Traceback (most recent call last): File "D:\online shopping\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\online shopping\env\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response self.check_response(response, callback) File "D:\online shopping\env\lib\site-packages\django\core\handlers\base.py", line 332, in check_response raise ValueError( ValueError: The view shop.views.get_product didn't return an HttpResponse object. It returned None instead. [19/Aug/2022 11:45:30] "GET /favicon.ico/ HTTP/1.1" 500 63121 [19/Aug/2022 11:45:33] "GET /account/cart/ HTTP/1.1" 200 8204 Not Found: … -
Application error after deploy django app on heroku
I have successfully built and deployed my DJANGO app on the HEROKU. During building the application collectstatic also is running smoothly. But after everything completed successfully when I tries to open my app it is showing me application error. I have adding my recent log with this question. If anyone needs more information to analyze and give the solution then I can provide that also. recent log of heroku 2022-08-19T05:51:36.278162+00:00 app[api]: Initial release by user smit.dpatel9924@gmail.com 2022-08-19T05:51:36.278162+00:00 app[api]: Release v1 created by user smit.dpatel9924@gmail.com 2022-08-19T05:51:36.436285+00:00 app[api]: Enable Logplex by user smit.dpatel9924@gmail.com 2022-08-19T05:51:36.436285+00:00 app[api]: Release v2 created by user smit.dpatel9924@gmail.com 2022-08-19T05:51:57.696877+00:00 app[api]: Stack changed from heroku-20 to heroku-22 by user smit.dpatel9924@gmail.com 2022-08-19T05:51:57.713307+00:00 app[api]: Release v3 created by user smit.dpatel9924@gmail.com 2022-08-19T05:51:57.713307+00:00 app[api]: Upgrade stack to heroku-22 by user smit.dpatel9924@gmail.com 2022-08-19T05:52:24.000000+00:00 app[api]: Build started by user smit.dpatel9924@gmail.com 2022-08-19T05:53:26.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/4295d649-fdd6-4ff6-a915-07b881b4b295/activity/builds/614228a6-7a78-4922-ba2d-2bc5f297c905 2022-08-19T05:53:39.192112+00:00 app[api]: Release v4 created by user smit.dpatel9924@gmail.com 2022-08-19T05:53:39.192112+00:00 app[api]: Set DISABLE_COLLECTSTATIC config vars by user smit.dpatel9924@gmail.com 2022-08-19T05:53:45.000000+00:00 app[api]: Build started by user smit.dpatel9924@gmail.com 2022-08-19T05:55:33.534266+00:00 app[api]: Attach DATABASE (@ref:postgresql-symmetrical-16068) by user smit.dpatel9924@gmail.com 2022-08-19T05:55:33.534266+00:00 app[api]: Running release v5 commands by user smit.dpatel9924@gmail.com 2022-08-19T05:55:33.545559+00:00 app[api]: Release v6 created by user smit.dpatel9924@gmail.com 2022-08-19T05:55:33.545559+00:00 app[api]: @ref:postgresql-symmetrical-16068 completed provisioning, setting DATABASE_URL. … -
How to get domain in django template
I'm trying to build unsubscribe link in my email template but problem is i'm using seperate function in my utilites.py file to render my template and don't have access to request. This function is called by schedular in backend. I tried request.build_absolute_uri and other things but not able create the absulute link templates <body> <section class="tour section-wrapper container" id="notify-form"> <table id='datatable'></table> {{ content|safe }} {# <a href="{{ request.build_absolute_uri}}{% url 'delete' %}?email={{ sub_email }}">Unsubscribe</a>#} {# <a href="{% if request.is_secure %}https:/{% else %}http:/{% endif %}{{ request.get_host }}{{ request.build_absolute_uri }}{{ object.get_absolute_url }}{% url 'delete' %}?email={{ sub_email }}">Unsubscribe</a>#} <a href="{% if request.is_secure %}https://{% else %}http://{% endif %}{{ domain }}{% url 'delete' %}?email={{ sub_email }}">Unsubscribe</a> </section> <!-- /.tour </body> --> commented code is also what i tried tried using Sites framework but that gives doamin as example.com not what I expected utility method def send_notification(dataframe, email): subject = 'That’s your subject' from_email = 'xxxx@gmail.com' # 'from@example.com' text_content = 'That’s your plain text.' subscriber_email = QueryDetails.objects.get(email=email) domain = Site.objects.get_current().domain html_content = get_template('mail_template.html').render({'content': dataframe.to_html(classes=["table-bordered", "table-striped", "table-hover"]),'sub_email': subscriber_email, 'domain': domain}) Expected out put is if in local domain will be http://127.0.0.1/unsub/?email=xxxx@gmail.com if in production then http://whateverproductiondomain.com/unsub/?email=xxxx@gmail.com But if i run the program with one of commented code in … -
How to get all the users who have any relationship with a specific user in Django
I`m making a System where I need to get all the users who have a relationship with a specific user(the logged-in user). The relationship is like this I need all the users who have been joined by a user who also has been joined by another user until it reaches the logged-in user. My problem is to get the relationship to work so I can get all the users who have a relationship with the logged-in user I haven`t done any coding yet to show you guys... Please help me... Thank you, -
In Django Queryset, is there a way to update objects by group that are formed by group_by(annotations)?
My specific example : class AggregatedResult(models.Model) : amount = models.IntegerField() class RawResult(models.Model) : aggregate_result = models.ForeignKey(AggregatedResult, ...) type = models.CharField() date = models.DateField() amount = models.IntegerField() In this specific example RawResults have different type and date, and I'd like to make a queryset to aggregate them. so for example, I'd do something like : RawResults.objects.values("type","date").annotate(amount_sum = Sum("amount")) then I'd create AggregatedResult objects based off the results. Problem here is I have a ForeignKey relationship to AggregatedResult and I would like to assign proper foreignkey to RawResult, base off which objects have contributed to which result. for instance, assume : RawResult idx type date amount 1 A 10-04 10 2 A 10-04 8 3 A 10-05 7 4 B 10-04 5 running the queryset above will give me aggregated values, however, I want to update the RawResult objects to be properly mapped to AggregatedResult. So like : [ {A, 10-04, 18} new AggregatedResult(1) <- RawResult 1,2 should have aggregate_result = 1 {A, 10-05, 7} new AggregatedResult(2) <- RawResult 3 should have aggregate_result = 2 {B, 10-04, 5} new AggregatedResult(3) <- RawResult 4 should have aggregate_result = 3 ] I have moderate size of RawResult(500k ish), and little types (~15 types), and …