Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stream video from s3 bucket to web player
Python + Django + Video.js. As pet-project I want to do my own cloud web – gallery. I made S3 – compatible object storage and uploaded video file in it. I want to stream this video on my web-site, like YouTube, without downloading full video. I know, that I can create a pre-signed URL, but I think it isn’t the best idea, because I would have many video files. I found «_raw_stream» method, as I understand, in response I get bytes. How I can use this method to transmit video in web-player? Or maybe you please tell me another way, how to stream video from s3 bucket to web player? THX! -
Duplicate push notification at a time send via firebase
I face a weird problem, with push notifications using Firebase and Django fcm-device. When a file upload is done, then push notification to desired users. I ensure that this function calls only one time after the video upload is completed. Suddenly 20-30 notifications are sent for one single upload to desired users. This issue stays approx 5-10h. But now it's fine again, no problems. Then what would be the reason for this behavior? -
I want to create a like counter in Django, but I get an error
I want to create a like counter for an exercise project that receives and counts the number of likes from self and displays them in templates . from django.db import models from django.contrib.auth.models import User from django.urls import reverse class post(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='posts') title = models.CharField(max_length=150) body = models.TextField() slug = models.SlugField() create = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.title} - {self.update}' # Define a get_absolute_url() method to tell Django # how to calculate the canonical URL for an object. def get_absolute_url(self): return reverse('home:post_detail',args=(self.pk ,self.slug)) def likes_count(self): ....... #My problem is here class Vote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,name='uvote') post = models.ForeignKey(post,on_delete=models.CASCADE , name='pvote') def __str__(self) -> str: return f'{self.uvote} ---- {self.pvote.slug}' I tried this code (told to me in my tutorial) def likes_count(self): return self.pvote.count() -
Get download count via download attribute with Django
I'm doing a project with Django, like a music player, this is my models: class Song(models.Model): """Model representing a song""" name = models.CharField( max_length=200, help_text=_('Enter a song name')) image = models.ImageField( upload_to='cover_image') content = models.FileField(upload_to='songs') artist = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField( default=False, help_text=_('Check this box to make the song public') ) since I already configured the uploaded folder and all, all I have to do in my templates is adding the download attribute to the tag and it will download file for the user <a href="/media/{{ i.content }}" download="{{ i.name }}" type="video/mp4"> <button class="btn btn-outline-danger">Download Song </button> </a> This works flawlessly, however it proves to be quite difficult if I want to get the download count for the song. I'm thinking of giving it the tag an onclick attribute so when I click the download button it will trigger a javascript function to send a hidden form to views to increment the downloads value. However this I think is quite convoluted so I wonder if there is a better way to do this. -
How to Connect Azure Mysql Database with Django Project
I am Trying to Connect my Django Project with the Azure Mysql Database but it's show this error continuously: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2003, "Can't connect to MySQL server on 'dummyserver.database.windows.net' (timed out)") and this is easily able to connect with the Azure Data Studio, don't know why it's not working in this Django Project, may you please help me out in any way so that i can be able to make this done, even i am able to make the connection to the local Mysql Server and able to migrate the Table and Models, but when i am trying to do this with Azure Mysql Database, then not and it's sure that all the details i put in the configuration. i had also followed these links: https://learn.microsoft.com/en-us/samples/azure-samples/azure-sql-db-django/azure-sql-db-django/ Hope for Help, ASAP i just want to make this Connection Done and able to migrate all my models to the Azure Mysql Database, with the help of my Django project -
How to use raw query in django tastypie and join tables?
I am trying to use a raw query in django tastypie queryset. But django is throwing me the following exception: <error_message>'RawQuerySet' object has no attribute 'filter'</error_message> I also tried using ModelName.objects.filter() to join different tables. It's not working either. Django throwing the following exception: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. My tastypie models.py file looks like this: import datetime from django.db import models from tastypie.resources import ModelResource from logsheet.models import * from generation.models import * from django.contrib.auth.models import User from tastypie.authentication import BasicAuthentication from django.db.models import Sum class EnergyPlantWiseResource(ModelResource): class Meta: present_time = datetime.datetime.today() previous_month = present_time.month - 1 present_year = present_time.year queryset = EnergyPlantWise.objects.raw('SELECT 1 id, SUM(ep.kwh), f.name FROM energy_plant_wise ep, fuel f WHERE ep.fuel_id=f.id AND MONTH(ep.date)=%s AND YEAR(ep.date)=%s GROUP BY f.name',[previous_month, present_year]) # queryset = EnergyPlantWise.objects.all() resource_name = 'epw' allowed_methods = ['get'] excludes = ['id'] -
Receiving Keywords from Spring Boot to Django
I'm working on sending a keyword from Spring Boot to Django. @RestController public class ProfileController { private final RestTemplate restTemplate; public ProfileController(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @GetMapping("/sendprompt") public ResponseEntity<String> sendprompt(@RequestParam String keyword) { try { System.out.println("keyword: " + keyword); String djurl = "http://localhost:8000/makingimage"; Map<String, String> map = new HashMap<>(); map.put("keyword", keyword); restTemplate.getForEntity(djurl, String.class); return ResponseEntity.ok("success"); } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred."); } } } ProfileController.java Since I haven't implemented the frontend yet, I'm manually entering the keyword in the URL like this:http://localhost:8080/sendprompt?keyword=castle class MakingImage(APIView): def t2i(self, prompt, negative_prompt): try: r = requests.post( 'https://api.kakaobrain.com/v2/inference/karlo/t2i', json={ 'prompt': prompt, 'negative_prompt': negative_prompt }, headers={ 'Authorization': f'KakaoAK {REST_API_KEY}', 'Content-Type': 'application/json' } ) response = json.loads(r.content) return response.get("images")[0].get("image") except Exception as e: print(f"An error occurred in t2i: {e}") return None image_url = None def making_image(self, request): response = None if request.method == "GET": print("get") prompt = request.GET.get("keyword") negative_prompt = "sleeping cat, dog, human, ugly face, cropped" response = self.t2i(prompt, negative_prompt) else: print("post") return Response(response, status=status.HTTP_200_OK) models.py When a keyword is sent from Spring Boot to the address at 8080, Django receives the keyword and utilizes the t2i function to generate an image within the making_image function. from django.urls import path from .views … -
Django exclude() query with violation
I have this model: class SettingMenus(models.Model): cat = models.ForeignKey(Setting, on_delete=models.CASCADE, related_name="menus", null=True) index = models.SmallIntegerField(validators=[MaxValueValidator(32766)], default=0) name = models.CharField(max_length=100, null=True) path = models.CharField(max_length=200, null=True, blank=True) parent = models.ForeignKey('self', null=True, blank=True, related_name='sub_categories', on_delete=models.CASCADE) role = models.ManyToManyField(UserRole, related_name="settingMenus", blank=True) tables = models.ManyToManyField(AppModels, related_name="setting_menus", blank = True,) And a query in view: nv1menus = SettingMenus.objects.filter( cat__company__name=company, cat__application="common", index=0, role__in=request.user.groups.all() ).exclude(sub_categories__role__in=request.user.groups.all()).distinct() How I can violating sub_categories__role__in=request.user.groups.all() which is in exclude? I have tried: sub_categories__role__in!=request.user.groups.all() or not sub_categories__role__in=request.user.groups.all() But not works. -
Merging multiple querysets using union is showing error with Count in annotate
I have a simple django app and I am trying to merge multiple querysets using union but one of my queryset contains annotate with Count. I mean it is showing each UNION query must have the same number of columns LINE 1: ...::date GROUP BY 1 ORDER BY 15 DESC) UNION (SELECT I am using Count in annotate most liked blog post and most viewed blog post like filter_blog_posts = Blog.objects.annotate(f=Count("likes") + Count("views")) and other query which I am merging with is new_blogs = Blog.objects.order_by("-date") and like merged_q = Blog.objects.none() merged_q = merged_q.union(filter_blog_posts) merged_q = merged_q.union(new_blogs) and When I remove annotate then it is working fine but not with it. I saw many topics on showing error with annotate with union like this. and I also tried with it by adding values but my other queries will also need to be changed but I don't want to limit the fields. Any help would be much appreciated. -
How to show a list with ManyRelatedManager objects in nested serializer Django
I have a Category model (Parent) and a Product model (Child) with a FK to Category. Several products may belong to the same category and I want to show all products of a Category in GET request. But as a result, I get duplication of categories by the number of products. For example: If I have one cftegory "Milk" and 3 products with FK to "Milk", my GET method returns 3 instances of Category. my models.py class Category(models.Model): name = models.CharField(max_length=255) sku = models.CharField(max_length=255, blank=True, default="") class Product(models.Model): class Meta: default_related_name = "product" category = models.ForeignKey(CatalogItem, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=255, blank=True, default="") my views.py class CategoryApi(ListModelMixin, GenericViewSet): serializer_class = ProductCatalogSerializer def get_queryset(self): return Category.objects.all() My serializers.py class ProductCatalogSerializer(serializers.ModelSerializer): class Meta: model = CatalogItem fields = ( "sku", "name", "marketplaces", ) sku = serializers.SerializerMethodField(help_text="category SKU") marketplaces = serializers.SerializerMethodField(help_text="category products info") @staticmethod @swagger_serializer_method(serializer_or_field=serializers.CharField) def get_sku(obj): return obj.offer_id @staticmethod @swagger_serializer_method(serializer_or_field=serializers.ListField) def get_marketplaces(obj): results_data = MarketplaceInProductSerializer(list(obj.product.all()), many=True).data # results_data is a list with ordered dicts return results_data class MarketplaceInProductSerializer(serializers.Serializer): id = serializers.IntegerField(help_text="ID продукта") name = serializers.SerializerMethodField(help_text="Категория") @staticmethod @swagger_serializer_method(serializer_or_field=serializers.CharField) def get_name(data): return data.name I want to get in response a list with existing categories and products in it. -
Filtering ManyToMany in Django-Admin/Django-Form by related field
I want to filter my ManyToMany by related fields in the Django-Admin (create/edit object). For example i have 3 Models: Model 1 - Boardgame: Name (CharField), Genre (ForeignKey) Model 2 - Location: Name (CharField), Boardgame (ManyToMany) Model 3 - Genre: Name (CharField) Now in the django-admin when i edit a location i can add and remove boardgames via horizontal-filter. Now i want an extra select Field where i can define a genre, so the manyToMany choices change based on what i select on the genre-select. But i can't find an option to Include the genre-select To filter by the genre-select Anyone here having an idea, how to solve this? What i tried so far: Tried the django_advanced_filter because google lead me to it -> It is just for filtering in the "overview"-tab Tried to find a function that can do this natively in the admin -> Didn't find anything Had the idea to accomplish this via a modelsForm but wasn't able to find a possibility to add there a filter tab. Read something about django_filters, that maybe an option, but didnt find a possibility to integrate it in the forms.py -
strawberry-django isAuthenticated
I'm having a go at the Strawberry library for a new project. Actually, I'm quite liking it! However, in this project, pretty much everything needs authentication. But reading through the documentations, I would need to declare extension[IsAuthenticated()] on every field. This is not very DRY, nor very error-proof when more people get involved in the development. Can you point me in the direction, of give some suggestions how to implement this on a schema-level; where one can exclude specific field? -
Django uploads, video, images, pdf etc
Please I really need a solution, I’ve been trying to figure out on how I could create a model field where images, videos, pdf and other related files can be uploaded. Just like instagram where you can upload your file with Just one field, please I really need the solution please 🙏🙏🙏🙏🙏 I’ve tried using filefield, but the image tag in HTML keep giving me an error, image field has no attribute file -
__str__ returned non-string (type NoneType) I don't even where is the problem
I was making which user allowed to do what and which doesn't allowed by watching a video series. After I did something, which I don't know, I couldn't delete one user. Then I added one more user to see could I delete that one. First I added one user on admin panel then I deleted it, it worked. But when I tried to add one user with register page I couldn't delete it. Then I looked the customer's on admin panel and I couldn't see the name there was '-' instead of the name of user. decoraters.py from django.shortcuts import redirect from django.http import HttpResponse def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not autherized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == "customer": return redirect('user') if group == "admin": return view_func(request, *args, **kwargs) return wrapper_function models.py from django.db import models from django.contrib.auth.models import User class Customer(models.Model): … -
How to implement google login in django?
I want to implement google login in Django without allauth or other packages. I wrote thisenter code here code. But only first function called " google_login is working ". google_call_back is not working and I can not capture user email. Here is my code. enter image description here -
I was trying to create register page by using `UserCreationForm` but getting empty `QueryDict` from post method
I was trying to create register page by using UserCreationForm but getting empty QueryDict from post method when I print it on console. There is no errors. I did research on it but could not figure it out. this is views.py file from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm # Create your views here. def register(request): print('\n\n\n\n',request.POST,'\n\n\n') if request.method == 'POST': form=UserCreationForm() if form.is_valid(): form.save() return redirect('home/') else: form=UserCreationForm() context={'form':form} return render(request,'register/register.html',context) and this is my template: {% block content %} <form method="POST" class="form-group" action="#%"> {% csrf_token %} {{form}} <button type="submit", name="register", value="register1", class="btn btn-success" > Register </button> </form> {% endblock %}``` When I hit register button on website I am getting this traceback: ```System check identified no issues (0 silenced). September 21, 2023 - 10:00:05 Django version 4.2.5, using settings 'proproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. <QueryDict: {}> [21/Sep/2023 10:00:11] "GET /register/ HTTP/1.1" 200 3702 <QueryDict: {}> [21/Sep/2023 10:00:11] "GET /register/ HTTP/1.1" 200 3702 -
Is there a Node.js/Express.js library/framework for quick CRUD API setup like Django REST Framework?
I am currently working on a project in Node.js with Express.js, and I'm looking for a library or framework that can streamline the process of creating REST API endpoints for CRUD operations on my models, similar to how Django REST Framework simplifies this task in Django. In Django, I can quickly set up a model like this: from django.db import models class Artist(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name Then, I create a serializer: from rest_framework import serializers from songs.models import Artist class ArtistSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Artist fields = ['url', 'id', 'name', 'songs'] And finally, a viewset: class ArtistViewSet(viewsets.ModelViewSet): """ API endpoint that allows songs to be viewed or edited. """ queryset = Artist.objects.all() serializer_class = ArtistSerializer filter_backends = [filters.OrderingFilter] ordering_fields = ['name'] ordering = ['-name'] With these few lines of code, I can create API endpoints for creating, reading, updating, and deleting Artist records, as well as add sorting and filtering functionality. It's a very convenient and efficient approach. I'm wondering if there is a similar library or framework in the Node.js/Express.js ecosystem that offers a similar level of simplicity and ease of use. I find that in Node.js, there tends to be more boilerplate code … -
Django Graphql Auth mutations failing with error unexpected keyword argument 'refresh_token'
In my project I am using below libraries for django graphql authentication, django-graphql-jwt django-graphql-auth PyJWT I am running below mutation and some other similar mutations. mutation Register { register( email: "appleorange@gmail.com" password1: "Abcd@2023" password2: "Abcd@2023" ) { success errors refreshToken token } } From yesterday suddenly all mutations started failing with error, { "errors": [ { "message": "Register.__init__() got an unexpected keyword argument 'refresh_token'", "locations": [ { "line": 47, "column": 5 } ], "path": [ "register" ] } ], "data": { "register": null } } I tried changing the library versions for above package by switching to the old one but that did not help. I don't understand what exactly changed. Please suggest. -
Why the self.field returns no value, but getting it from a query.get returns the value?
I have this function that receives self as a parameter and im trying to check some fields in the object. The problem is when i do this checking, the self.field returns nothing but when i do a get in the object the field returns the correct value. Look def aguardando_exames_email_html(self): pedido = PedidoPlaca.objects.get(pk=self.pk) exame_escaneamento = pedido.exame_escaneamento #returns the obj #exame_escaneamento = self.exame_escaneamento #returns nothing ... I just need to understand what happens in django in this case and when to use self and when to use the object from database. -
Python/Javascript Websocket disconnects after first message
I have this python code (Server) async def chatProcess(websocket): message = await websocket.recv() print(f"<<< {message}") ints = predict_class(message) res = get_response(ints, intents) print("Category"+ints) await websocket.send(res) print(f">>> {res}") async def main(): async with websockets.serve(chatProcess, "localhost", 8765): await asyncio.Future() # run forever if __name__ == "__main__": asyncio.run(main()) and this javascript client in my webpage let websocket = new WebSocket("ws://localhost:8765"); const generateResponse = (chatElement) => { const messageElement = chatElement.querySelector("p"); try{ websocket.send(userMessage); websocket.onmessage = function(event) { messageElement.textContent = event.data; console.log("[message] Data received from server:"+ event.data); return false; }; } catch(error) { console.log(error) messageElement.classList.add("error"); messageElement.textContent = "Somethings wrong. Try Again"; } finally{ chatbox.scrollTo(0, chatbox.scrollHeight); } But keeps disconnectong after first message and get this error enter image description here What can I do so that it doesn't disconnect and I can send messages between client and server? -
Installed module causes 'ModuleNotFoundError' when executing script from Python. How can I use installed modules in my scripts?
We develop using the django framework. When using subProcess.run() to run a python file, a pip installed module is causing a 'ModuleNotFoundError'. Is the module not loaded in the file executed by subProcess.run? Also, how do I use the module? The development environment is built on AmazonLinux2 within docker. ・Process for calling Python files # No error occurs in this file. import yaml script = os.path.join(os.path.dirname(__file__), "script.py") subprocess.run( [script, args1, args2], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) ・Python file to be called #!/usr/bin/env python3 # os is loaded import os import yaml def main() { ~~~~~~~~ } ・Error Description ModuleNotFoundError: No module named 'yaml' ・install pip install pyyaml -
SEO for every blog post in Django Python framework
I am working on Django application for rendering blog posts on various topics. As you know, in WordPress Yoast / math rank plug in there is an option for SEO for every blog post using meta tags. My question is can we use meta tags in the {% block content %} within the body of the blog post in Django, or otherwise. Bear in mind that Django documentation recommends, using meta tags in the base.html file and in the head section only. If we use the meta tags in the head section in HTML, then how it can be altered for each and every blog post. Thanks -
overriding behavior when 'submit' button clicked in Django
I am trying to develop a tennis ladder Django website that has classes for Player, Match, and Ladder. I have imported some dummy data and also have Create, Delete, Update, and List views for players and matches. But when a player is created, I need to also create a new Ladder object that will contain the new state of the ladder. Likewise, when a player is deleted (or is unavailable due to injury), the ladder state must change, and a new ladder is created. (I want to retain a historical record of each ladder state in case something is done by mistake ... this lets me revert to an earlier verson of the ladder). Finally, ladder positions change if a challenger defeats his or her opponent. Here's my question. How do I trigger such code in a DeleteView (e.g. deleting a player). For a CreateView, I use this approach: class PlayerCreateView(CreateView): model =Player num_players = Player.objects.count() context_object_name = 'player' fields = ['ranking', 'first', 'last', 'cell', 'email', 'availability'] template_name = 'player_create.html' success_url = reverse_lazy('players') def form_valid(self, form): response = super().form_valid(form) num_players = Player.objects.all().count() ladders = Ladder.objects.all() # <CALL CODE TO CREATE NEW LADDER OBJECT> return response But what about other scenarios … -
Django-channels Problems
Good day, I am currently learning how to implement WebSocket with Django and I have encountered some roadblocks. I'm using uvicorn and Django channels for my project, I am trying to implement a feature whereby I would be able to retain the previous message that I have been sent in a group chat. But this is my errors anytime I try to send messages. Traceback (most recent call last): File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 247, in run_asgi result = await self.app(self.scope, self.asgi_receive, self.asgi_send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/routing.py", line 116, in __call__ return await application( ^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/consumer.py", line 58, in __call__ await await_many_dispatch( File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/utils.py", line 50, in await_many_dispatch await dispatch(result) File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/asgiref/sync.py", line 479, in __call__ ret: _R = await loop.run_in_executor( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/db.py", line 13, in thread_handler return super().thread_handler(loop, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/asgiref/sync.py", line 538, in thread_handler return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/consumer.py", line 125, in dispatch handler(message) File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/generic/websocket.py", line 59, in … -
How can I perform a SQL JOIN using Django ORM when the models are not related?
I have two models that look like this: (tableA) class ModelA(models.Model): student_id = models.TextField() name = models.TextField() age = models.IntegerField() (tableB) class ModelB(models.Model): student_id = models.TextField() report_card_file_id = models.TextField() # Other fields in ModelB I created a sql query to join them that looks like this: SELECT tableA.*, tableB.report_card_file_id FROM tableA LEFT JOIN tableB ON tableA.student_id = tableB.student_id where tableB.report_card_file_id is not null; But how can I transform this query into Django orm so that I will have a QuerySet with student_id, name, age, and report_card_file_id? Here is some code I have, but I am not sure how to fill in the ?: a = ModelA.objects.all() a = a.annotate(?) I also tried using .raw() but then I get a RawQuerySet instead of just a QuerySet.