Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Periodic Tasks Django that update state
I created a Django server. I have a class instance that loads its data from the database, once it is loaded (i.e. once the Django dev server starts). What I want to achieve is that there is a recurring task, such that the instance reloads from the database, once every day. I.e. <instance>.load_db() should be called, once a day. I tried to configure a cron job that calls the function once a day using crontab package. However, this only spawns a new instance of the server, does a reload there, but does not update the state of the running instance of the server. I would need the server to simply execute the tasks itself, not spawn a new instance of the server. Any ideas on how you can achieve this? -
Django Graphene filter date field with startswith using year and month
I am using Django and Graphene and have created a GraphQL query to return purchase orders from my database. All orders have a date field associated with it to represent when the order was created. The values in this column are formatted like 2022-05-01 08:38:17+01 - I know this is a datetime field and will rename the column at some point. I am trying to create a filter for the user to only return data from a particular month in a given year. The filter value is represented like 2022-05 for year and month. I would like the GraphQL to filter the data returned for that year and month. I am trying to use the startswith value to do this but getting an error that it is not a date. I understand that it is not a valid date, but I can't figure out how to filter the date field using only the year and month. Schema class Purchases(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = purchase_orders interfaces = (relay.Node,) filter_fields = {'date': ['startswith']} connection_class = ArtsyConnection GraphQL Query { Purchases(first: 15, after: "", date_Startswith: "2022-05") { ... Response { "errors": [ { "message": "Argument \"date_Startswith\" has invalid value … -
Django update user POST HTTP/1.1 302 0
Help me, please. What am I doing wrong? I'm trying to update the user, I send a request, but I get 302 in response. My request: https://skr.sh/sEYdKhpyf1w [21/Jun/2022 10:54:24] "GET /clients/client_1/update HTTP/1.1" 200 8884 [21/Jun/2022 10:54:29] "POST /clients/client_1/update HTTP/1.1" 302 0 [21/Jun/2022 10:54:29] "GET /clients/client_1 HTTP/1.1" 200 11527 views.py class UpdateClient(UpdateView): model = Profile form_class = ClientForm template_name = 'admins/admin_update_client.html' context_object_name = 'client' def get_context_data(self, **kwargs): cl = Profile.objects.get(pk=self.kwargs['pk']) c = json.loads(cl.CategoryVU) ctx = super(UpdateClient, self).get_context_data(**kwargs) ctx['cats'] = c return ctx def post(self, request, pk): lis = request.POST.getlist('CategoryVU') res = dict((i, lis.count(i)) for i in lis) data = json.dumps(res) form = ClientForm(request.POST) cl = Profile() if (form.is_valid()): cl= Profile.update_client(cl, request, pk, data) return redirect('admin_client', pk) forms.py class ClientForm(forms.ModelForm): class Meta: model = Profile fields = ('name', 'phone', 'email') -
Access javascript variables in python function file(views.py) using django
I want to access javascript array variable into python function file(views.py). I stored data in array using javascript and want to get that data into python function for further process. show.html function getvalues() { var val = []; $(':checkbox:checked').each(function (i) { val[i] = $(this).val(); }); } views.py def show(request): selected = val[i] return render(request, "show.html", {}) I want to use val[i] into views.py show() function. If I need to use AJAX then how I can use AJAX? or there is some other way to access data -
Django template if expression not correct?
My Django template returns error as: (error at line 26 )Unused 'item' at end of if expression. I checked the reported lines as below and didn't where's the error in my code. Could anyone help me? In which line 26 is {%if cur_prj and item == cur_prj %} The whole snippet is as: {%for item in PROJS %} {%if cur_prj and item == cur_prj %} <option value={{item}} selected>{{item}}</option> {%elif not cur_prj item == my_case.project_name%} <option value={{item}} selected>{{item}}</option> {%else%} <option value={{item}}>{{item}}</option> {%endif%} {%endfor%} -
Page not found (404) in Django Output
my url.py urlpatterns = [ path("", views.index, name="blogHome"), path("blogpost/<int:id>/", views.blogpost, name="blogHome") ] my views.py django.shortcuts import render from .models import Blogpost # Create your views here. def index(request): return render(request, 'blog/index.html') def blogpost(request, id): post.Blogpost.objects.filter(post_id = id)[0] print(post) return render(request, 'blog/blogpost.html') my models.py from django.db import models class Blogpost(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=50) head0 = models.CharField(max_length=500, default="") chead0 = models.CharField(max_length=10000, default="") head1 = models.CharField(max_length=500, default="") chead1 = models.CharField(max_length=10000, default="") head2 = models.CharField(max_length=500, default="") chead2 = models.CharField(max_length=10000, default="") pub_date = models.DateField() thumbnail = models.ImageField(upload_to='blog/images', default="") def __str__(self): return self.title Error Error Image which i see in output Error in cmd Not Found: /blog/blogpost [21/Jun/2022 12:29:33] "GET /blog/blogpost HTTP/1.1" 404 2678 Please help me to solve this problem as soon as possible -
Django: Get average rating per user
Given the following, how can I make a query which returns a list of the average rating per user in friendlist? models.py class Beer(models.Model): id = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=150) ... class Checkin(models.Model): id = models.IntegerField(primary_key=True) rating = models.FloatField(blank=True, null=True) ... class FriendList(models.Model): user = models.OneToOneField(User, on_delete=CASCADE, primary_key=True) friend = models.ManyToManyField(User, related_name="friends") database (postgresql) user beer rating 1 1 4.2 1 1 3.5 1 1 4.0 2 1 4.1 2 1 3.7 My current query to get all friends checkins: Checkin.objects.filter(beer=1, user__in=friends.friend.all()) Which gives me something like: [{user: 1, rating: 4.2}, {user: 1, rating: 3.5},...,{user: 2, rating: 4.1}...] What I want is: [{user: 1, avg_rating: 4.1}, {user: 2, avg_rating: 3.8}] -
Python group a list of years, months to remove duplication of years
I have a table that contains orders, in which contains the date column. I am getting back the aggregate of the years, and months from that column so that I can use that data in a filter on the front end. I have managed to get this data back, however it is not formatted in the way I would like. Python years = purchase_orders.objects.filter(user_id=info.context.user.id).annotate(year=ExtractYear('date'), month=ExtractMonth('date'),).order_by().values_list('year', 'month').order_by('year', 'month').distinct() Data Returned <QuerySet [(2020, 3), (2021, 4), (2022, 1), (2022, 2), (2022, 3), (2022, 4), (2022, 5)]> Ideal Format <QuerySet [(2020, (3)), (2021, (4)), (2022, (1, 2, 3, 4, 5))]> -
NoReverseMatch at / Reverse for 'register_request' not found. 'register_request' is not a valid view function or pattern name
this is a shopping website my login and registration form is not working it is showing that no reverse path found error. this is my navbar template <div class="container py-5"> <p class="text-center">If you already have an account, <a href="{% url 'sweet:register_request' %}">login</a> instead.</p> </div> <div class="container py-5"> <p class="text-center">Don't have an account? <a href="/register">Create an account</a>. </p> </div> login.html this is my login template {% extends "base.html" %} {% load static %} {% block content %} {% csrf_token %} {{ login_form }} Login {% endblock %} home.html this is my registration template {% extends "base.html" %} {% load static %} {% block content %} Register {% csrf_token %} {{register_form}} {% endblock %} views.py register_request is function defined to register the form and login_request is to login into my website def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, "Registration successful.") return redirect('login_request') messages.error(request, "Unsuccessful registration. Invalid information.") form = NewUserForm() return render(request,"home.html",{"register_form": form}) def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, "You are now logged in as {username}.") return redirect("base.html") … -
chrome makes null endpoint request in django service
My env is django backend , vuejs from vite frontned. also using django-vite package in backend and nginx for proxy server. But when I depolyed all code to server, now I am getting null endpoint request. I can only see it in chrome browser. It doesn't appear in IE edge. Why does it happend? Do you guys have any idea? I left screenshot and service url http://3.35.61.148/ Can it be related to not using SSL(https) ? -
django allauth multiple custom forms for social sign up
I want to build 2 different custom forms, one for google sign up accounts, and one for facebook sign up accounts. Yet allauth only allow one custom form for all social sign up via the settings.py: SOCIALACCOUNT_FORMS = {'signup': 'accounts.forms.SignupFormSocial'} Is there a way to this ? Like pass in two different form to the overriden forms so I can choose which one to show based on the current provider. -
How to add extra per-Feed fields to a Django Feed (Specifically, a Django-iCal feed)
I am generating a per-user calendar feed. As part of the URL, I'm allowing event filters. I am struggling to figure out how to save that filter (or any arbitrary variable) to the specific Feed I am generating from the specific call. The method I thought would work is (coming from a C++ world) making a static variable that is shared amongst all Feed callers, which would lead to inconsistency when Feeds are being generated simultaneously. What is the proper way to do this? Reading through the Feed libraries, I see methods like feed_extra_kwargs() and item_extra_kwargs(), but I can't find examples or documentation on them that show how to use them. My URL: re_path(r'^ics/(?P<user_id>\d+)/(?P<params>[\w=;]+)/ical.ics$', EventFeed(), name='ics'), My Feed attempt: class EventFeed(ICalFeed): """ A simple event calender """ product_id = '-//icevite.com//Schedule//EN' timezone = 'UTC' file_name = "icevite.ics" filter = [] alarms = [] def get_object(self, request, user_id, params, *args, **kwargs): self.filter = [] try: split = params.split(";") for s in split: item = s.split("=") match item[0]: case "f": self.filter = list(item[1]) case "n": mins = int(item[1]) if mins: self.alarms.append(mins) return Player.objects.get(id=user_id) except: return None def items(self, player): responses = Response.objects.filter(mate__player=player) if self.filter: filtered = responses.exclude(response__in=self.filter) else: filtered = responses return filtered.select_related('game', … -
having trouble with saving the value of "gender" in update page
and I amd making a CRUD project,I have used radio button's for genders:male /female. I am able to successfully add the genders while adding new employee, however while updating the details, the gender which I selected isnt saved in the 'update' page. below is the code for gender in the 'Insert' page <tr> <td>gender</td> <td> <input type="radio" value="male" name="gender">male | <input type="radio" value="female" name="gender">female </td> </tr> below is the code for my 'Edit' page Male:<input type="radio" value="{{EmpModel.gender}}"> Female: <input type="radio" value="{{EmpModel.gender}}"> Since I am not sure what value I am supposed to put here, I added EmpModel.gender for both please help -
Pagination for Django search results (python)
I want to add pagination to my search results in django. This is my search function form views.py for the relevant (Jobs) module: def search(request): queryset_list = Job.objects.order_by('-publishing_date') if 'keywords'in request.GET: keywords = request.GET['keywords'] if keywords: queryset_list = queryset_list.filter(description__icontains=keywords) if 'state' in request.GET: state = request.GET['state'] if state: queryset_list = queryset_list.filter(location__iexact=state) if 'job_type' in request.GET: job_type = request.GET['job_type'] if job_type: queryset_list = queryset_list.filter(job_type__iexact=job_type_choices) if 'industry' in request.GET: industry = request.GET['industry'] if industry: queryset_list = queryset_list.filter(industry__icontains=industry_choices) if 'salary' in request.GET: salary = request.GET['salary'] if salary: queryset_list = queryset_list.filter(salary__lte=salary) context = { 'location_choices':location_choices, 'salary_choices':salary_choices, 'job_type_choices':job_type_choices, 'industry_choices':industry_choices, 'jobs':queryset_list, 'values':request.GET, } return render(request, 'jobs/search.html', context) This is pagination function from the same file: def index(request): jobs = Job.objects.order_by('-publishing_date').filter(is_published=True) paginator = Paginator(jobs, 6) page = request.GET.get('page') paged_jobs = paginator.get_page(page) context = { 'jobs': paged_jobs } return render(request, 'jobs/jobs.html', context) Both of them work (search returns results and pagination works on listing page) however I want to have pagination too for my search results. I am very new to python and django, and assume there is more elegant way of writing my search function, so please do not hesitate to let me know your thoughts. -
How to configure my django settings.py for production using postgresql
I'm already deploying my django app. However, I don't know what I should place in my host instead of using localhost. note: this works perfectly if I run it locally. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'trilz', 'USER': 'postgres', 'PASSWORD': 'franz123', 'HOST': 'localhost', 'PORT': '5432', } } -
Unable to run index migration in OpenSearch
I have a docker compose running where a django backend, opensearch & opensearch dashboard are running. I have connected the backend to talk to opensearch and I'm able to query it successfully. I'm trying to create indexes using this command inside the docker container. ./manage.py opensearch --rebuild Reference: https://django-opensearch-dsl.readthedocs.io/en/latest/getting_started/#create-and-populate-opensearchs-indices I get the following error when I run the above command root@ed186e462ca3:/app# ./manage.py opensearch --rebuild /usr/local/lib/python3.6/site-packages/OpenSSL/crypto.py:8: CryptographyDeprecationWarning: Python 3.6 is no longer supported by the Python core team. Therefore, support for it is deprecated in cryptography and will be removed in a future release. from cryptography import utils, x509 Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 224, in fetch_command klass = load_command_class(app_name, subcommand) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 37, in load_command_class return module.Command() File "/usr/local/lib/python3.6/site-packages/django_opensearch_dsl/management/commands/opensearch.py", line 32, in __init__ if settings.TESTING: # pragma: no cover File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 80, in __getattr__ val = getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'TESTING' Sentry is attempting to send 1 pending error messages Waiting up to 2 seconds Press Ctrl-C to quit I'm not sure where I'm going wrong. Any help would be … -
How to display ID for each form in Django Formset
Need to make the UI more ordered, can i have indexing for the forms in formset or access the form ID? <div class="card"> <div class="card-body"> <div id="form-container"> {% csrf_token %} {{ formset1.management_form }} {% for form in formset1 %} <div class="test-form"> {% crispy form %} </div> {% endfor %} <button id="add-form" type="button" class="btn btn-primary">Add Another Request </button> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </div> -
Upload PDF File via Django Admin, Users Download from Link on Template
I'm trying to allow users to download a PDF file that I've previously uploaded to the MEDIA_ROOT folder via the admin console. I've emulated the answer in this post, however it's incomplete and I can't figure out how to fix this. Hoping someone can spot my issue in the code below. settings.py # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = str(BASE_DIR) + "/media/" # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory that holds static files. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = str(BASE_DIR) + "/static/" # URL that handles the static files served from STATIC_ROOT. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' models.py from django.db import models # Create your models here. class ResumeModel(models.Model): pdf = models.FileField(upload_to="resume_app/media/resume/") # So this file gets uploaded to root > media > resume_app > media > resume admin.py from django.contrib import admin from .models import ResumeModel # Register your models here. admin.site.register(ResumeModel) views.py from django.shortcuts import render from .models import ResumeModel # Create your views here. … -
Cannot save model inside celery task exception?
I have a chain of celery tasks to manage talking to an older XML polling based API, so I need to be able to make one call to a remote API per task, and pass the results to the next task. Some of these APIs throw weird errors, so I'm trying to come up a general way to catch and make sure all my errors end up in the database so I have an audit trail of what happened. No matter what I've tried, when I try to write to the database from within a caught exception block, it refuses to save it. I assume there's something going on in Django, but I can't find much to suggest why in the docs. I know I'm catching the error, because I do see log entries. I'm trying to do something like the following: import traceback import sys import logging log = logging.getLogger('daniTest') @celery_app.task() def dmtest(d:dict): log.info(f'DM: Test: dict: {d}') try: raise Exception('Just a test.') except Exception as e: exc_info = sys.exc_info() errStr = ''.join(traceback.format_exception(*exc_info)) log.error(errStr) # d has a jobId key I can use to link to DB: dbJob = MyModel.objects.get(job_id=d['jobId']) dbJob.error_messages = errStr dbJob.save() Is there a way to make … -
ValueError: source code string cannot contain null bytes when I install a new requirements.txt file
I did a pip install -r requirements.txt and after that, realized that my development server could nolonger start. I have been unable to tell which of the files installed caused this. I even tried to re-install a previous requirements.txt file I had before this one but the nothing changed. Could anyone be having a clue on what exactly is happening from this traceback message? Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File … -
Django templates using buttons for Boolean fields
I have a preferences page that has many Boolean fields. I created an UpdateView and when I use {{ form.as_p }} in my template it works, but I am trying to create individual buttons for each option instead of checkboxes. I couldn't find a way to make it work in my template. models.py class Preference(models.Model): user = models.OneToOneField("User", on_delete=models.SET_NULL, null=True) option1= models.BooleanField(default=False) option2= models.BooleanField(default=False) option3= models.BooleanField(default=False) option4= models.BooleanField(default=False) views.py class preferencesview(UpdateView): model = Preference form_class = PreferenceForm success_url = reverse_lazy("profiles:preferences") forms.py class PreferenceForm (forms.ModelForm): class Meta: model = Preference exclude = ['user'] I want to have individual buttons for each option and a submit button to save the changes. Please let me know if you have any documentation or tutorials. Thanks! -
Django-Tables2-Column-Shifter <frozen importlib._bootstrap> Error When Getting Table Class
I am using the Django-Tables2-Column-Shifter Django library successfully in my Django application from one of my applications named app1. I am running into a bizarre error when attempting to use the same logic to use Django-Tables2-Column-Shifter from another app app2 which uses a different model. The error that I am receiving is below: File "/home/datavizapp/.virtualenvs/venv/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'project_name' The code posted below all works as expected. The error arises in the get_table_class code when I change the following: tabledata_table = get_table_1_class( self.table_class_version )(tabledata_queryset) to tabledata_table = get_table_2_class( self.table_class_version )(tabledata_queryset) Below is "views.py" inside app2 from project_name.app1.models import Table1 from project_name.app2.models import Table2 from project_name.app2.tables import get_table_1_class from project_name.app2.tables import get_table_2_class #from project_name.app1.tables import get_table_1_class # This also works if uncommented (original code is in app1) from django_tables2_column_shifter.tables import ( ColumnShiftTableBootstrap4 ) from … -
Got error when trying to remove auth and user tables in Django migration
I am using Django to create rest apis. But as I notice whenever I migrate tables to databases tables such asauth_ user_ got migrated as well. I want to prevent that so I remove some rows of INSTALLED_APPS in settings.py INSTALLE D_APPS = [ # 'django.contrib.admin', # 'django.contrib.auth', # 'django.contrib.contenttypes', # 'django.contrib.sessions', # 'django.contrib.messages', # 'django.contrib.staticfiles', 'devices', 'django_crontab', 'drf_yasg', ] But I go this error, when trying to run py manage.py makemigrations. Traceback (most recent call last): File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\registry.py", line 156, in get_app_config return self.app_configs[app_label] KeyError: 'admin' ...................... LookupError: No installed app with label 'admin'. -
Django: Is it possible to get field values for a list of objects in bulk?
This is probably a silly question, but for some reason I just cannot find a way to do this: I am working on a recommendation engine in Django, which recommends movies based on the similarities between your taste and other users' tastes. Since every database access takes time, I try to use bulk methods as much as possible. However, at one point I need to get the movie that is associated with a certain vote, and I just cannot figure out how to do this in bulk: The relevant models are: class Movie(models.Model): id = models.AutoField(primary_key=True) ... voters = models.ManyToManyField(Voter) ... and class MovieVote(models.Model): rating = models.FloatField() weight = models.FloatField() voter = models.ForeignKey(Voter, on_delete=models.CASCADE, null=True) movie = models.ForeignKey(Movie, on_delete=models.CASCADE, null=True) ... And the one line that currently takes 80%(!) of the time of the whole recommendation process is: for otherVote in listOfOtherVotes: ... movie = otherVote.movie ... Is there any way to look up the foreign key "movie" for the whole list of votes at once? And ideally return it as a dictionary that maps each vote to the movie? -
Iterate through fields using array Django
I have this model: class Some_model(models.Model): field_1 = models.CharField(max_length=200, blank=True, null=True) field_2 = models.CharField(max_length=200, blank=True, null=True) and this function: # create a function to upload a model object given a json object def upload_object_values(model, json_values, keys=None): if json_values: # assign a value to each key which is a the field in the given model for key, value in json_values.items(): setattr(model, key, value) # if the object has keys to check if keys: # check if exists using the keys when called like this: upload_object_values(Some_model(), {'field_1': 'val', 'field_2': 'val_2'}, ['field_2']) It would do a get or create inside the upload_object_values function using the fields inside the keys parameter (e.g.: field_2 as the parameter). Some_model.objects.get_or_create(field_2='val_2')