Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Odd behaviour on REST: Update/patch View doesn't allow get method and returns 405 when called via requests
Similar questions have been asked before, but I can't seem to fix my problem with the answers. I am trying to partially update an object and I overwrote the partial_update method in REST's generic UpdateAPIView but when I call this view via requests I get a 405:get method not allowed-response. What is extremely odd is that my code was working for about 2 weeks and now all of the sudden I get this error. I'm banging my head against a wall and can't seem to figure this out. In my view I am doing this: class BuildingUpdateAPI(UpdateAPIView): serializer_class = BuildingSerializer def partial_update(self, request, *args, **kwargs): """Patches building specified in URL with data in request.""" network = Network.objects.get(name=self.kwargs["name_network"]) building = network.buildings.get(name=self.kwargs["name_building"]) serializer = BuildingSerializer(building, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return JsonResponse(status=200, data=serializer.data) msg = ( "Error message" ) return JsonResponse(status=400, data=msg, safe=False) My serializer is simple, it only defines the fields (but I can provide it if it helps). In other answers it is said that REST looks for a get-method and can't find it. But I am calling this not via get, but via patch: ep = "http:localhost:/path/to/update/" data { "update_field": "123" } r = requests.request("patch", url=ep, data=data, headers=get_headers()) Other … -
for in django template doesn't showed up
Hi i have work on a website and use Django for it's Back-End, i use for to show list of users(for example) according to below code: <table id="example" style="width:100%" class="table table-striped table-bordered"> <thead> <tr> <th>Username/Email</th> </tr> </thead> <tbody> {% for user in userslist %} <tr> <td>{{user}}</td> </tr> {% endfor %} </tbody> </table> it runs without any error but nothing showed up in place of tag. Pythons part: def show_users(request): users = User.objects.all() template = loader.get_template('user/users_table.html') users_list = [] for i in range(len(users.all())): users_list.append(users[i].get_username()) print(users_list) return HttpResponse(template.render({"users_list":users_list}, request)) -
Fetch parent model objects while calling child model in django
I have models Artist and Album, The album view displays all the albums by all artists, the url of single-album contains artist_slug and album_slug I want to show all albums of every artist with a href link to single-album with two arguments artist_slug and album_slug, If any one knows how to do that, Please help! The code below works as i wanted, but shows error music.models.Artist.DoesNotExist: Artist matching query does not exist. models.py class Artist(models.Model): artist_slug = models.SlugField(max_length=200) class Album(models.Model): artist = models.ForeignKey(Artist) album_slug = models.SlugField(max_length=200) urls.py path('<str:artist_slug>/<str:album_slug>/', views.singleAlbum, name='single-album'), views.py def albums(request): artists = Artist.objects.all() return render(request,'template_name', {'artists':artists}) Template {% for artist in artists %} {% if artist.album_set.all %} {% for album in artist.album_set.all %} <a href="{% url 'single-album' artist.artist_slug album.album_slug %}">Some Text</a> {% endfor %} {% endif %} {% endfor %} -
Django cookie-cutter multisite on the same IP
I'm wondering if it' s possible to run many instances of dockerized Django cookie-cutter [traefik] on the same IP [VPS] via port 443 ? ERROR: for traefik Cannot start service traefik: driver failed programming external connectivity on endpoint example_traefik_1 (b42b55428fbfa12df55b670c6823b52e7367f3425e4e2bc7d36e002578460380): Bind for 0.0.0.0:443 failed: port is already allocated traefik.yml log: level: INFO entryPoints: web: # http address: ":80" web-secure: # https address: ":443" flower: address: ":5555" certificatesResolvers: letsencrypt: # https://docs.traefik.io/master/https/acme/#lets-encrypt acme: email: "contact@example.com" storage: /etc/traefik/acme/acme.json caServer: https://acme-staging-v02.api.letsencrypt.org/directory # https://docs.traefik.io/master/https/acme/#httpchallenge httpChallenge: entryPoint: web http: routers: web-router: rule: "Host(`example.com`)" entryPoints: - web middlewares: - redirect - csrf service: django web-secure-router: rule: "Host(`example.com`)" entryPoints: - web-secure middlewares: - csrf service: django tls: # https://docs.traefik.io/master/routing/routers/#certresolver certResolver: letsencrypt flower-secure-router: rule: "Host(`example.com`)" entryPoints: - flower service: flower tls: # https://docs.traefik.io/master/routing/routers/#certresolver certResolver: letsencrypt middlewares: redirect: # https://docs.traefik.io/master/middlewares/redirectscheme/ redirectScheme: scheme: https permanent: true csrf: # https://docs.traefik.io/master/middlewares/headers/#hostsproxyheaders # https://docs.djangoproject.com/en/dev/ref/csrf/#ajax headers: hostsProxyHeaders: ["X-CSRFToken"] test-compress: compress: {} services: django: loadBalancer: servers: - url: http://django:5000 flower: loadBalancer: servers: - url: http://flower:5555 providers: # https://docs.traefik.io/master/providers/file/ file: filename: /etc/traefik/traefik.yml watch: true -
Accessing User ID from window.LocalStorage
I have a DjangoRestFramework / Vue.js application. For now I was getting my logged user with this.requestUser = window.localStorage.getItem("username"); I just needed my requestUser to check if a user was logged or not. Now I have to "POST" data via an endpoint, but in my backend, DRF is expecting an ID not a string value. So I checked my window.localStorage with the 'developer tool' and only my username value is stored, not its value. I have few options: -create a new endpoint that will fetch an user ID from its value. And then on created() run a function that will save it into window.localStorage -modify my models and serializers so I can use my user value instead of its ID to interact with my endpoints. -or simply there is a configuration that I am not aware of than can save my user.id as well as my user.username In DRF I am using plain django.contrib.auth for my User model. What is the best approach for my problem? -
Creating new model instance through views.py including args through a url
I am trying to create a new model instance every time a url is accessed. so far, I have the function working in my views.py, but when the new model instance is created, the fields are empty (because I have not specified what I'd like in those fields in views.) views.py def session_invent(self): session = Session() # I can add field data in here, but I want to get it via the URL session.save() messages.success(self, f'session invented!') return redirect('blog-home') urls.py path('session/invent/', views.session_invent, name="session-invent"), models.py class Session(models.Model): uid = models.CharField(max_length=50) cid = models.CharField(max_length=50) qid = models.CharField(max_length=50) aid = models.CharField(max_length=50) session_date = models.DateTimeField(auto_now_add=True) def qid_plus_aid(self): return '{}_{}'.format(self.qid, self.aid) def __str__(self): return self.uid def get_absolute_url(self): return reverse('session-detail', kwargs={'pk': self.pk}) Ok, so here is what i am trying to pull off: right now if i enter mywebsite.com/session/invent/ a new Session model instance is created with empty fields. Is there a way I can fill in those fields with args in the URL? For example, something like... mywebsite.com/session/invent/?uid=test_uid&cid=test_cid&qid=test_qid&aid=test_aid -
Using choices in a field in django models
This is my models.py: class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True) paymentstatus = ( ("Payment Successful", "Payment Successful"), ("Payment Pending", "Payment Pending"), ("Payment Failed", "Payment Failed"), ) status=models.CharField(max_length=20,blank=True,null=True,choices=paymentstatus) In my views.py I have a view which checks whether the payment has been completed or not in that I want to set the payment status (for example if payment is completed then I want to set status as Payment Successful). This is how I tried it: if response_dict['RESPCODE'] == '01': order.status=Payment Successful order.save() print('order successful') But this is not working. Also once done I want to have it on a html template so would iterating like {{order.status}} would be correct? If not then how do I access it in my template. -
Deploying a django app with django channels to GCP
I have a django app where I started using django channels for websockets. The app is deployed on GCP app engine. The app works fine for my REST APIs but I am not able to establish web sockets from my clients. The problem is connecting to a redis instance by the django channels layer. I get the following error: TimeoutError: [Errno 110] Connect call failed ('10.39.182.27', 6379) I did set up a serverless VPC connector based on the documentation. How to fix this error? -
Passing a dataframe as a queryset in django
I have a modelformset that I am trying to initialize with a dataframe but keep getting the error 'list' object has no attribute 'ordered' views.py def myView(request): dd = defaultdict(list) sales = df.to_dict('records', into=dd) saleformset = modelformset_factory(Sale, form = forms.editSale) formset = saleformset(queryset=sales) -
How to send an email after 11 months from the last technical checkup last_checkup datefield()?
So I have built an awesome ticketing system for a company that makes GPS embedded chips. Once a year they service their products and I've made a model field last_checkup. After 11 months from the last checkup they need to get notified that soon they will have to do it again. Do you have any ideas how do I write a logic for that? Here is the code. Thanks. _/I_ They will later change the date so it works next year. class tickets(models.Model): name = models.ForeignKey(devices, on_delete=models.CASCADE, blank=True, null=True) location = models.CharField(max_length=200) company = models.CharField(max_length=200) serial_number = models.CharField(max_length=200) problem = models.CharField(max_length=1000) contact_number = models.CharField(max_length=200) status = models.BooleanField(default=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="authorname", null=True) executive = models.ForeignKey(executives, on_delete=models.CASCADE, blank=True, null=True) email_as_send = models.BooleanField(default=False) SLA = models.DateField() # Here is the question. They have yearly checkups of devices someone buys. # They need to be notified 11 months from the last checkup. last_checkup = models.DateField() def __str__(self): return self.problem def save(self): if self.status == True: send_mail("subject", "Zatvoren ticket", "jankojovicic351@gmail.com", [self.author.email], fail_silently=False) super().save() -
Is there any way to maintain the same url parameter in django?
What I want to do is the following, when I click on the href tag I want to use the same str:sym I was using in the other url, but I'm not sure if it's possible to do it, so I would appreciate a lot your answers, thanks in advance. The one that isn't working is the AddPostView urls.py app_name = 'app1' urlpatterns = [, path('stock/<str:sym>/add_post',AddPostView.as_view(), name='addpost'), path('stock/<str:sym>/', views.StockView, name = 'stock'), ] Views.py class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'app1/createpost.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def StockView(request, sym): stock_posts = Post.objects.filter(stock__symbol=sym) stock_sym = get_object_or_404(StockNames,symbol = sym) return render(request, 'app1/stockview.html', {'stocks':stock_posts, 'sym':sym, 'stock_sym':stock_sym}) models.py class StockNames(models.Model): name = models.CharField(max_length=255) symbol = models.CharField(max_length=255) def __str__(self): return self.symbol class Post(models.Model): title = models.CharField(max_length= 255) header_image = models.ImageField(null = True, blank = True, upload_to = 'images/') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank = True, null = True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name = 'blog_posts') stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE) def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('app1:article-detail', args=(self.id,)) template (Here, in … -
pip3 install mysqlclient got error in centos ec2 instance
pip3 install mysqlclient got error in centos ec2 instanceERROR: Command errored out with exit status 1: command: /usr/local/bin/python3.8 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ewu2x4x2/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-ewu2x4x2/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-bc7b78u8 cwd: /tmp/pip-install-ewu2x4x2/mysqlclient/ Complete output (12 lines): /bin/sh: mysql_config: command not found /bin/sh: mariadb_config: command not found /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-ewu2x4x2/mysqlclient/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-ewu2x4x2/mysqlclient/setup_posix.py", line 65, in get_config libs = mysql_config("libs") File "/tmp/pip-install-ewu2x4x2/mysqlclient/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Please help to install mysql client in centos -
Is there a way with Django's ModelAdmin to display a different field when rendering a ManyToMany select box?
I have a Django model with a ManyToManyField. When rendering the admin page to add an instance of the model, ModelAdmin renders a select box with options like SomeModel object(7c158809-4c9b-4d44-b3ac-9f225b8bd076 (the model uses a uuid as its primary key). How can I get Django admin to render the select box with a different, more friendly field? -
Connecting Django to Heroku live postgresql database
I have deployed my django/react app using Heroku but when i try to log in into the deployed app it does not work, the API file in react that uses Django login url throws an error. Weirdly enough, when i run locally Django server python manage.py runserver the app in Heroku suddenly works and i'm able to login and view app data but when i stop the Django server i'm not able to access login back to the app in Heroku. Also whenever my Django server is running locally and i make some API request on the app in Heroku, i can see the API call method(s) being called on the local running Django server. This is not to be. Not sure if the Database is set up right to be used by Heroku. NB: In Heroku, i already have a postgresql addon settings.py import os from datetime import timedelta import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '5ce825272901fd427dcbd299ccade51d6e9f679630530801' DEBUG = (os.environ.get('DEBUG_VALUE') == 'True') ALLOWED_HOSTS = ['crm-django-react.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'djoser', 'accounts', 'product', 'clients', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # ADDED - HEROKU 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', … -
Django -Email is appearing in console instead of being sent to recipient
I am using a business email for my website. Website has two parts, One is "Contact Us" form where email will be sent to my [business email]. Second part requires email to be sent from [business email] to customers emails. I have set up django mail as per documentation: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'cp1.mywebsitebox.com' EMAIL_HOST_USER = '*********' EMAIL_HOST_PASSWORD = '********' EMAIL_PORT = 26 DEFAULT_FROM_EMAIL = '*******' Issue is that, first part goes well. Email recieves successfully at [business email] but second part is totally not working. Instead of being sent to recipient, it appears only in console. Can anyone suggest what the issue is? -
I want to create tables in Django database by which may have dynamic fields by uploading a excel or csv sheet from a web interface
How can we create a DB table in db using django framework by uploading a unique CSV/excel files In front end there will be an upload button for uploading a CSV/excel and once used click submit a table should be created based on the fields -
how to write DATE_FORMAT(now(), "%m/%d/%Y") in django raw query
how to write this query in django orm or django raw query SELECT * FROM rfq_db.RFQapp_rfq where quotes_due >= DATE_FORMAT(now(), "%m/%d/%Y") GROUP BY rfq_id order by quotes_due desc; -
Django: Setting IP address for login
I'm launching my first web page with Django using heroku as a platform. My database is an Azure Database with AD Password. My application is working fine locally and when I deploy it it compiles successfully, but when I try to log in inside the app (I used django authentication to create my login interface) I get the following error: ('42000', "[42000] [unixODBC][Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot open server 'myserver' requested by the login. Client with IP address 'ip.ip.ip.ip' is not allowed to access the server. To enable access, use the Windows Azure Management Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range. It may take up to five minutes for this change to take effect. (40615) (SQLDriverConnect)") After doing some research, I noticed that heroku uses a dynamic IP address, so I went to look into their addons and found QuotaGuard Static IP, which supposedly routes all traffic through their static IPs. I already added the two IPs they give me and installed the addon, but I still get the same error. Do I need to do something inside my error to route all my requests … -
Django - Update an instance after boolean is flipped from False ==> True
I am trying to figure out the functionality for updating an instance, when a Boolean is flipped from False to True. On Account registration, I am creating an Account instance and a Company instance. If the company is already in the database, I want to add the new user to that company, as well as update the Company info(address, phone, etc.), only if the admin approves of this. I thought the best way was to add a Boolean in the Account model, ==> business_claim_approved = False is the default. This is a complete snippet. I'm going to cut down the company_obj filtering, since it is actually pretty long, I will just provide a simple filter here. company_obj = Company.objects.filter(name=company.title()) if not company_obj: """If no company match, create new one""" new_company = Company.objects.create( name=company.title(), zip=int(zip_code), primary_email=email, website=website, phone_no=phone_no, street=street, city=city, state=state, ) new_company.employee.add(user) else: """If company match, Add employee to company if approved my admin""" company_obj.phone_no = phone_no company_obj.street = street company_obj.city = city company_obj.zip = zip_code company_obj.state = state company_obj.primary_email = email company_obj.website = website if user.business_claim_approved: company_obj.employee.add(user) company_obj.save() Now, I thought that if I went directly into the admin and flipped that users Boolean business_claim_approved to True, it would … -
How to use AdminStackedInline in OneToOneField
I am Facing an Issue in Admin Stacked Inline any help will be highly appreciated, and Please also Suggest me this DB Architecture is Good? or is there any Good Approach to achieve this? In my Project I have Two Roles Student and Teacher, and Student will also become the Teacher and Teacher also become Student. Both cases Vice Versa. Here Below is My Base Model. class User(AbstractUser): class Meta: verbose_name =_("Student") verbose_name_plural = _("Students") ROLE = ( ('STUDENT', 'Student'), ('TEACHER', 'Teacher'), ('STUDENT-TEACHER', 'Student-Teacher') ) username = models.CharField(verbose_name=_('Username'), max_length=100, unique=True) email = models.EmailField(verbose_name=_('Email'),max_length=200,blank=False,null=False) dob = models.DateField(verbose_name=_("Date of Birth"), blank=False, null=True) phone_number = models.CharField(verbose_name=_("Phone Number"), blank=True, null=True, max_length = 13) role = models.CharField(max_length=50, choices=ROLE, blank=False, null=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'username' def __str__(self): return self.username and below is my Teacher Model class Teacher(models.Model): class Meta: verbose_name =_("Teacher") verbose_name_plural = _("Teachers") TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones)) GENDER_CHOICES = ( ('MALE', 'Male'), ('FEMALE', 'Female') ) LEVEL_CHOICES = ( ('BEGINNER', 'Beginner'), ('INTERMEDIATE', 'Intermediate'), ('ADVANCED', 'Advanced') ) pke = models.BigIntegerField(primary_key=True) user = models.OneToOneField(User, blank=False, null=False, on_delete=models.CASCADE) profile_image = models.ImageField(verbose_name=_("Profile Image"), blank=True, null=True, upload_to="teacher_image", default="/dummy.png") gender = models.CharField(verbose_name=_("Gender"), choices=GENDER_CHOICES, blank=True, null=True, max_length=100) level = … -
Change status of field of type FileField in Django REST
I have this model model.py class File(models.Model): file = models.FileField(blank=False, null=True, upload_to =file_directory_path) STATUSES = ( (0, 'Deleted'), (1, 'Active'), ) status = models.IntegerField(verbose_name='Status', choices=STATUSES, default=1) def __str__(self): return self.file.name and this srializer serializers.py class FileSerializer(serializers.ModelSerializer): file = serializers.FileField() class Meta: model = File fields = '__all__'#('file') def to_representation(self, instance): representation = super().to_representation(instance) file = { "url": representation.pop("file"), "size": instance.file.size, "name": instance.file.name, #"date": instance.file.date, } representation['file'] = file return representation How i can change status field without file field. Because i return error AutoFilterSet resolved field 'file' with 'exact' lookup to an unrecognized field type FileField. Try adding an override to 'Meta.filter_overrides'. See: https://django-filter.readthedocs.io/en/master/ref/filterset.html#customise-filter-generation-with-filter-overrides after send PUT method with JSON: { "id": 45 "status": 1 } -
how to loop all json data in django templates
features: 0: properties: name, age 1: properties: name, age 2: properties: name, age What is the easy way to display all properties in a loop in django templates. All are json data from api requests. -
change primary key field using django south
I had models in this fashion : class Item(PolymorphicModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Module(PolymorphicModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.TextField() class Sub(Model): class Sub2(Model): I wanted to change the database schema to class Module(Item): As i found out it was not very easy, i decided to add a OneToOneField to Module which points to item: class Module(PolymophicModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) item = models.OneToOneField(Item, on_delete=models.CASCADE) Im thinking this would be similar to inheritance . Now i want to make the one to one field as the primary key while not losing existing data in Module. I first tried running custom migrations while setting OneToOne fields null=True. Then i populated Item table with ids same as Module ids using management commands. Then i run my migrations: from django.db import migrations def populate_share_items(apps, schema_editor): Module = apps.get_model('els', 'Module') Item = apps.get_model('els', 'Item') for module in Module.objects.all(): module.item = Item.objects.get(id=module.id) module.save() class Migration(migrations.Migration): dependencies = [ ('els', '0002_module_tenant_share_item'), ] operations = [ migrations.RunPython(populate_share_items), ] Now i have entries in items with ids same as Module ids. When i call, Item.objects.all() Im expecting to get Module instances when calling get_real_instance() and i want to change the primary key field … -
Update database with data from custom form
Ok, so i want to update info about user with custom form that looks like this. <form action="" > <!--csrftoken--> <input type="text" placeholder="Your new name" name="name"> <input type="text" placeholder="Your new email" name="email"> <input type="text" placeholder="Your new number" name="number"> <button type="submit" class="raise">Submit</button> </form> How to update user with the data that was filled. Let's say user fills in the number and the email field and the rest was left blank, email and number are changed but the name was left untouched. I was thinking about form prepopulating, but this calls for another database request and i want to avoid that. def updateCustomer(request): current = request.user if request.method == 'POST': newphone = request.POST['newPhone'] newemail = request.POST['email'] newname = request.POST['name'] addingToBase = Customer.objects.get(user=current) xD = addingToBase(email=newemail,name=newname,phone=newphone) xD.save() return redirect('home') -
Django query for filter/selection (master / detail)
I have the following models defined: class Submission(models.Model): uuid = models.UUIDField(db_index=True, default=uuid4) student_item = models.ForeignKey(StudentItem, on_delete=models.CASCADE) status = models.CharField(max_length=1, choices=STATUS_CHOICES, default=ACTIVE) team_submission = models.ForeignKey( TeamSubmission, related_name='submissions', null=True, db_index=True, on_delete=models.SET_NULL ) class TeamSubmission(TimeStampedModel): uuid = models.UUIDField(db_index=True, default=uuid4, null=False) course_id = models.CharField(max_length=255, null=False, db_index=True) item_id = models.CharField(max_length=255, null=False, db_index=True) team_id = models.CharField(max_length=255, null=False, db_index=True) submitted_by = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) status = models.CharField(max_length=1, choices=STATUS_CHOICES, default=ACTIVE) class StudentItem(models.Model): student_id = AnonymizedUserIDField() course_id = models.CharField(max_length=255, blank=False, db_index=True) item_id = models.CharField(max_length=255, blank=False, db_index=True) I am trying to figure out the Django syntax that given a list of StudentItem.student_id's, will give me back StudentItem.student_id for the StudentItem.student_id's that have an existing Submissions. Initially, I tried experimenting with 'prefetch_related' as: TeamSubmission.objects.prefetch_related('submissions') but it only provides me submission information and I can't figure out how to get student_id. Yes I know I will also have to 'filter' as well.