Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to tick those group by fetching groups based on user id in django
In the below image the user is in three groups so I want while updating the user the groups that user in should be checked. how can I achieve this ? I am unable to get how to achieve this in Django for now I fetching the all groups from database. {% for group in groups %} <tr> <td>{{group.name}}</td> <td><input type="checkbox" name="add_group[]" id="group-{{group.id}}" value="{{group.id}}"></td> </tr> {% endfor %} -
Unable to integrate Odoo with Django and getting error "erppeek.Error: Invalid username or password" . Please help me integrate odoo to django
I have followed the below article to integrate Odoo with Django: https://axistechnolabs.medium.com/guideline-for-odoo-integration-in-django-python-8c3bed069c8c My seetings.py configuration ODOO_HOST = { 'USER': 'vishnu', 'PASSWORD': 'password@123', 'HOST': 'http://localhost', 'PORT': 8069, 'DB': 'test1' } INSTALLED_APPS = [ 'djangodoo', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', How can I solve this, please help I have followed the below article to integrate Odoo with Django: https://axistechnolabs.medium.com/guideline-for-odoo-integration-in-django-python-8c3bed069c8c and run odoo server & django server but getting error: "erppeek.Error: Invalid username or password" -
Why do I get an API GET error as an anonymousUser even when using IsAuthenticatedOrReadOnly?
Im learning Django followed a book and tutorials. Anyways I started my own project, where users can create Posts for other to see. My problem comes when someone is not logged in and makes a GET request ie:PostListCreate below, the api crashes even tho I have permissions as IsAuthenticatedOrReadOnly. I get the error TypeError: Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x104d2f760>. Also I have models.ForeignKey(User, on_delete=models.CASCADE) in the model.py for Post model. Saw this might have something to do with it but unsure. Have spent three hours researching it and can't find a solution. What do I need to change or edit to be able to have a successful GET request without authentication. api/views.py from rest_framework import generics, permissions from .serializers import PostSerializer from post.models import Post class PostListCreate(generics.ListCreateAPIView): serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_queryset(self): user = self.request.user return Post.objects.filter(user=user).order_by('-created') def perform_create(self,serializer): serializer.save(user=self.request.user) class PostRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView): serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_queryset(self): user = self.request.user return Post.objects.filter(user=user) model.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) sold = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title -
django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0)
DATABASES = { 'default': { # 'ENGINE': 'sql_server.pyodbc', 'ENGINE': 'mssql', 'NAME': 'DatabaseName', 'HOST': 'ServerName', 'USER': 'LoginId', 'PASSWORD': 'LoginPass' # 'OPTIONS': { # 'DRIVER': 'SQL Server Native Client 11.0' # # 'DRIVER': 'ODBC Driver 13 for SQL Server', # } #, 'Extra_Params':'Trusted_Connection=True'} } } I already have SQL Server 11.0 installed, also ODBC 13 Driver installed Also configured System DSN as well. Please suggest. -
Can't change Latitude and Longitude after creating in GeoDjango
I have a model of store models.py class Store(models.Model): title = models.CharField(max_length = 50) point = models.PointField(null = True, blank = True) deleted = models.BooleanField(default=False) I set a form to create a store where the latitude and longitude can be converted into a point forms.py class StoreForm(forms.ModelForm): latitude = forms.FloatField( min_value = -90, max_value = 90, required = True, ) longitude = forms.FloatField( min_value = -180, max_value = 180, required = True, ) class Meta(object): model = Store exclude = ['deleted'] widgets = {'point': forms.HiddenInput()} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) coordinates = self.initial.get('point', None) if isinstance(coordinates, Point): self.initial['longitude'], self.initial['latitude'] = coordinates.tuple def clean(self): data = super().clean() latitude = data.get('latitude') longitude = data.get('longitude') point = data.get('point') if latitude and longitude and not point: data['point'] = Point(longitude, latitude) return data I used this form to add Store in my HTML frontend and when I check my backend data is in there. this form helps to show latitude and longitude fields and when I submit it automatically converts into a point When I want to update the store I used the exact same form to update, and I can see the previously added latitude and longitude value in charfield(as usual I used … -
How to make calculation inside annotate?
This one when I run generates error qs = User.objects.annotate(days=(datetime.now() - F("created_at")).days) AttributeError: 'CombinedExpression' object has no attribute 'days' How can I make that calculation as an annotation When I run this code, it wroks fine qs = User.objects.annotate(days=(datetime.now() - F("created_at"))) -
Django models for astra datastax db
I have developed a site on Django. Initially, I used Django's default Database which is Sqlite3. Now I want to use Astra Datastax DB which is Cassandra. I am not able to convert Django.dB - models into Cassandra.cqlengine - columns function. I have suffered on the Internet and didn't find appropriate documents which could help me. -
How to deploy my site ( React, Django, Selery, Selenium ) which is containerized ( Docker, Docker-Compose )?
Here I title it has 'how to deploy' since I have many doubts in this. My Work Overview: I am using React for my Frontend and Django for my Backend. In this, I used Selenium for WebScrapping which will be carried out on Celery. I deployed it in Okteto Problem Overview: I tried to fully containerise this using Docker and Docker-Compose. But, I am facing multiple problems with this. Ideas: I want my backend only accessed by my front end. and also selenium, celery should be accessed only from my backend. My front end should only access my backend, not any other APIs. The frontend request should be handled within the server( like the local host ) so that the request time will be reduced. Codes: Dockerfile in Backend: FROM python:3.10.9-slim-bullseye RUN apt-get update \ && apt-get install -y --no-install-recommends --no-install-suggests \ build-essential default-libmysqlclient-dev \ && pip3 install --no-cache-dir --upgrade pip WORKDIR /Backend COPY ./requirements.txt /Backend/ RUN pip3 install --no-cache-dir -r /Backend/requirements.txt COPY . /Backend/ EXPOSE 8000 RUN python3 manage.py makemigrations && python3 manage.py migrate CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] Dockerfile in Frontend: FROM node:19-bullseye-slim RUN apt-get update WORKDIR /Frontend COPY package-lock.json package.json /Frontend/ RUN cd /Frontend/ && npm i … -
Django aggregate calculating incorrectly because of many-to-many join in queryset
We have a model with a many-to-many relationship with another model, and doing a Sum aggregation on it seems to multiply the result by the number of many-to-many relationships. Example models below: class Attendee(models.Model): name = models.TextField() category = models.TextField() class Event(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() attendees = models.ManyToManyField(Attendee, related_name="event") class CalendarEvent(models.Model): calendar = models.TextField() event = models.ForeignKey(Event, related_name="calendar_events") We filter out some records based on Attendee, and then aggregate the duration of the events. queryset = queryset.filter(event__attendee__category="Accountant") queryset = queryset.annotate(duration=models.ExpressionWrapper( models.F('event__end_date') - models.F('event__start_date'), output_field=models.fields.DurationField() )) Whenever we run the aggregation at the end, all duration values would be multiplied by the number of Attendees associated with the Event/CalendarEvent. For example, if the event is 15 minutes long and has 4 attendees, we would expect the duration to be 900 seconds, but instead it's 3600 seconds. We noticed in the raw PSQL query that there is a LEFT OUTER JOIN against Attendees, so we tried removing the Attendee filter and it gave us the proper data. Is there any way to aggregate across a relationship like this without the joined results getting mixed in? -
Djoser not sending verification email with Google Workspace
I'm making a Django Webapp following the tutorial here. I have gotten everything to work up to a certain point. When I send the POST request to my djoser endpoint with my user information, I get back the same response he did in the video with status 201 and the name email and id fields presented back. However, I do not get a confirmation email like he does. The salient difference is that I am not using a vanilla gmail account like the demonstrator is. I have a custom domain hosted through Google Domains for which I also have a Google Workspace account. I can access this account's gmail inbox through the gmail website, and I can send and receive emails fine. However, confirmation emails will not send. I additionally followed the steps in this guide and they still would not send. Worth noting is that when I look at the google account's log in history, my app password has no record of being used. Any insight would be helpful. Here is the section of my settings.py that contains the relevant settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.Emailbackend' EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'admin@DOMAINNAME.net' EMAIL_HOST_PASSWORD = '**** **** **** ****' … -
regex_search: could not find match for (?:v=|\/)([0-9A-Za-z_-]{11}). when i add in youtube link (start=seconds) in django
I am currently working on a youtube video-embedded project in Django. I also use javascript but when I add some parameters in a youtube link using javascript for example https://www.youtube.com/embed/T6xslkut6JA?start=4 it's getting an error regex_search: could not find a match for (?:v=|/)([0-9A-Za-z_-]{11}). I spend a lot of time but I can't find any solution here is my javascript code: <script> let H; url = document.getElementById("url").innerHTML;//decleare url that get youtube link vedio = document.getElementById("vedio");// id that declear in <embed > tag function myFunction(value) {//value is in millisecond this function convert millisecond in second console.log("clicked"); console.log(value); var seconds = ((value % 60000) / 1000).toFixed(0); H = url+"?start="+seconds; console.log(url); vedio = document.getElementById("vedio").src = "H"; console.log(H); } </script> this is an error that i get -
direnv cannot find .envrc file even it does exist
I set up a virtual environment for a Django-React project. I have created the .bashrc in the user home directory, and .envrc file in the root folder of the project repo. But when I tried 'direnv allow' it always return '.envrc does not exit' with a weird referenced folder path. Can someone please help? direnv allow error direnv status I'm doing it on Windows 11. I tried to re-install everything and change the position of the folder from E to C driver. I also tried to rename the folder to anything else to see if any of it results in the weird folder path. But the error message remains. -
create seperate radio button using djang forms
I am trying to create radio buttons using modelform. The problem I'm having is that I can't get the radio buttons to separate, and it's also displaying a blank field. Here is what i am saying . Here is the html code for this one. <div id="cid_68" class="form-input jf-required"> <div class="form-multiple-column" data-columncount="2" role="group" aria-labelledby="label_68" data-component="radio"> <span class="form-radio-item" > <span class="dragger-item"></span> <!-- <input type="radio" aria-describedby="label_68" class="form-radio validate[required]" id="input_68_0" name="q68_typeA68" value="staff" required="" onclick="myFunction(0)"/> <label id="label_input_68_0" for="input_68_0">Staff</label> --> {{form.designation}} </span> <span class="form-radio-item"> <span class="dragger-item"></span> <!-- <input type="radio" aria-describedby="label_68" class="form-radio validate[required]" id="input_68_1" name="q68_typeA68" value="student" required="" onclick="myFunction(1)"/> <label id="label_input_68_1" for="input_68_1">Student</label> --> </span> </div> </div> </li> Here's what i want to achieve models.py DESIGNATION = ( ("Staff", "Staff"), ("Student", "Student"), ) class User(AbstractUser): username = models.CharField(max_length=9, default="", unique=True) avatar = models.ImageField( blank=True, null=True, default="avatar.svg", upload_to="images", validators=[validate_pic_extension]) password2 = models.CharField(default="", max_length=128, verbose_name="Confirm Password", null=True, blank=True,) email = models.EmailField(default="", max_length=255, unique=True) designation = models.CharField(default="", choices=DESIGNATION, max_length=255, null=True, blank=True) staff_id = models.CharField(default="", max_length=255, null=True, blank=True, verbose_name="Staff Id") matric_no = models.CharField(default="", max_length=255, null=True, blank=True, verbose_name="Matric Number") lib_user = models.CharField(default="", max_length=255, choices=LIBUSER, null=True, blank=True, verbose_name="Library User") library_id = models.CharField(default="", max_length=255, null=True, blank=True, verbose_name="Library Card Id") def __str__(self): return self.username forms.py class Profile(forms.ModelForm): class Meta: model = User fields = [ "username", … -
How to write testcase for django apis which has jwt?
I have python django project which has jwt implemented. And otp system and hash implementation for verifying email so any to write test cases for it. I dont want to test every models and serializers. Just want to test api end points if its working or not If anyone has any kind of example of it can share please -
Trouble Inheriting a function that renders data in a class containg a django generic view
First, I have model (Entry), where one field, 'prompt', is where I want to store text, "You suck bro!", in my django admin database. The second field, 'body', is a text editor I want to show on my html page. enter image description here In my views file, I have a function: def indexx(request), which renders text from the admin database, field 'prompt' on to my html page. views.py def indexx(request): entry = Entry.objects.all() return render(request, "entries/entries.html", {"ents" : entry}) urls.py from django.urls import path from .views import indexx urlpatterns = [ path("", indexx) ] This only renders text from django models: field ('prompt'). enter image description here Next, in my views file, I have a class, class EditEntryView(CreateView), where "(CreateView)", from "django.views.generic import CreateView". This allows me to render the text editor on my html page. The vies and urls are under the same python files as well. views.py class EditEntryView(CreateView): model = Entry # form_class = PostEntry fields = ["body" ] template_name = "entries/entries.html" urls.py from django.urls import path from .views import EditEntryView urlpatterns = [ path("", EditEntryView.as_view(), name="entries") ] This class renders the text editor. enter image description here My goal is to render the two separate … -
Difference between icontains and iregex in django
I am looking for solution of an usecase where i need to return search results even for part of a matching input text ex: if input text is man and the data that we have is ["manmohan", "manchester", "map"], then i should be returning ["manmohan", "manchester"] i was searching across the net on how to implement it using django, and saw two probable methods, icontains and iregex my questions here are which suits my usecase? what is the difference between these 2? -
Heroku deployment of django project causing: Exception Type: ProgrammingError
I have tested this locally and it works fine. When I deploy to Heroku it deploys fine and serves the home page. Though When I try to sign up and create a new user I get a Internal 500 error and get the following error message. Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) The above exception (relation "accounts_customuser" does not exist LINE 1: SELECT 1 AS "a" FROM "accounts_customuser" WHERE "accounts_c... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/edit.py", line 184, in post return super().post(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/edit.py", line 152, in post if form.is_valid(): File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/forms.py", line 205, in is_valid return self.is_bound and not self.errors File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/forms.py", line 200, in errors self.full_clean() File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/forms.py", line 439, in full_clean self._post_clean() File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/auth/forms.py", line 129, in _post_clean super()._post_clean() File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/models.py", line 498, in _post_clean self.validate_unique() File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/models.py", line 507, in validate_unique self.instance.validate_unique(exclude=exclude) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 1226, in validate_unique errors = … -
Is it a django rest framework good practise?
I am developing a restaurant management system where there are 4 types of user : admin, chef, driver (who delivers food) and the customer, and i am using django rest framework to create my restful api. Howeve I am stuck at the authentication process, since django doesn't have multiple users, i've read a lot of tutorials and stackoverflow questions and answers including : How to implement multiple user types with different roles and permissions in Django? How to Implement Multiple User Types with Django django best approach for creating multiple type users Creating multiple user types and using proxy models I didn't want to use the proxy model, since i didn't want to violate django rule for no multiple users, so i've created my solution but i want to know if it is good or bad or violate some good practises and if it will cause me headaches in the Future. models.py file : class UserRoles(models.TextChoices): ADMIN = 'admin', 'Admin' CUSTOMER = 'customer', 'Customer' CHEF = 'chef', 'Chef' DRIVER = 'driver', 'Driver' class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=100, unique=True) last_name = models.CharField(max_length=50) first_name = models.CharField(max_length=50) is_admin = models.BooleanField(default=False) role = models.CharField(max_length=50, choices=UserRoles.choices) is_customer = models.BooleanField(default = False) is_chef = models.BooleanField(default … -
InterfaceError: cursor already closed
We have a Django 4.0.4 site running. Since upgrading from Python 3.10->3.11 and Psycopg2 from 2.8.6->2.9.3/5 and gunicorn 20.0.4->20.1.0 we've been getting random InterfaceError: cursor already closed errors on random parts of our codebase. Rarely the same line twice. Just kind of happens once every 5-10k runs. So it feels pretty rare, but does keep happening a few times every day. I've been assuming it's related to the ugprade, but it may be something else. I don't have a full grap on why the cursor would be disconnecting and where I should be looking to figure out the true issue. Psycopg version: 2.9.5 & 2.9.3 Python version: 3.11 PostgreSQL version: 12.11 Gunicorn The site had been running for 1-2 years without this error. Now it happens a few times every day after a recent upgrade. -
Django 4 - TransactionTestCase - Postgresql sqlflush error
My code: Django 4.1 I am using multiple postgresql schemas for my models, postgresql12 with out-of-box ubuntu 20.04 setup. I am performing unit tests of some code which uses transactions. migrations are created When running other non-transaction tests with django TestCase, everything works normal. When running transaction test with TransactionTestCase (even with empty test function), this happens: django.db.utils.NotSupportedError: cannot truncate a table referenced in a foreign key constraint DETAIL: Table "users_user_permissions" references "auth_permission". HINT: Truncate table "users_user_permissions" at the same time, or use TRUNCATE ... CASCADE. ... django.core.management.base.CommandError: Database test_mike3 couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the expected database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run. django-admin sqlflush: BEGIN; TRUNCATE "django_content_type", "auth_group_permissions", "django_session", "auth_group", "auth_permission", "django_admin_log" RESTART IDENTITY; COMMIT; My solution I have gone into code and added _fixture_teardown(self) override to my ExampleTestCase(TransactionTestCase): basically changed allow_cascade=True in flush command. Since by this documentation: https://docs.djangoproject.com/en/4.1/topics/testing/advanced/ not setting available_apps might cause memory leaks, I will probably set all my apps to it so allow_cascade is set to True automatically. Original django … -
How to I get ForeignKey and M2M Django Ninja when making a post request
Am expecting to input the album_id which is a ForeignKey to my Music model and also the genres which is a ManyToManyField to the Music model also. This how I setup the Schema through the create_schema from ninja.orm from ninja import ModelSchema, Schema, Field from ninja.orm import create_schema from .models import Music MusicSchemaIn = create_schema(Music, name="MusciSchemaIn", exclude=['id', 'song_duration', 'slug', 'page_view', 'created'], base_class=Schema) This is my code for making a post request # upload music @router.post('/musics') def create_music(request, data: MusicSchemaIn): music = Music.objects.create(**data.dict()) return {'id': music.id} The error I get when a make a post request using the ModelSchema I created. Traceback (most recent call last): File "C:\Users\Jesse\Desktop\apps\venv\Lib\site-packages\ninja\operation.py", line 99, in run result = self.view_func(request, **values) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jesse\Desktop\apps\punga_play\music\views.py", line 22, in create_music music = Music.objects.create(**data.dict()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jesse\Desktop\apps\venv\Lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jesse\Desktop\apps\venv\Lib\site-packages\django\db\models\query.py", line 669, in create obj = self.model(**kwargs) ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jesse\Desktop\apps\venv\Lib\site-packages\django\db\models\base.py", line 541, in __init__ _setattr(self, field.name, rel_obj) File "C:\Users\Jesse\Desktop\apps\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 237, in __set__ raise ValueError( ValueError: Cannot assign "0": "Music.album" must be a "Album" instance. -
Celery alternative for very long running tasks
I'm searching for an alternative for Celery to process heavy long-running tasks (24 hrs +). Currently I'm using django + celery + redis, but I'm always running into strange behavior like that the worker simply freezes and does not consume tasks anymore ... Now I'm searching for something that is more designed to handle extremely long-running tasks for video conversion. Can anyone provide some advice, what might be the best choice here? I also need to be able to spin up periodic tasks. Thanks in advance -
How can I Log In user automatically after checking comparing user.email_verification_token?
My idea is to call LoginUser after checking user.email_verification_token == token and pass user's email and password, but there is a problem because I don't how to pass them as instance of django.http.HttpRequest. Could you help me guys? @api_view(['POST']) def verify_email(request, pk, token): try: user = User.objects.get(id=pk) except User.DoesNotExist: raise AuthenticationFailed('User not found!') if user.expiration_date < timezone.now(): return AuthenticationFailed('expired_token') if user.email_verification_token == token: user.is_email_verified = True user.save() return Response('message: success') return Response('message: Verification Rejected') @api_view(['POST']) def LoginUser(request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') ........ ........ -
Django not showing up all fields using objects with select_related
i'm facing an annoing bug in Django and i don't know how i can solve it. I'm trying to show up names from one other table using INNER JOIN but isn't working. Just to clarify, i have two database canaisAssoc and formatosAssoc, i'm trying to show up from canaisAssoc the name of the canais and from formatosAssoc the name of the formato, if you take a look at my views.py, i'm using ajax, because i need to choose one value from one select in template to fill up others, the issue is, when i run the canaisAssoc.objects.select_related('idCanal').filter(idSite_id = site, ativo = True).all() if i run this print(channels.query) The return of the query is: SELECT campanhas_canaisassoc.id, campanhas_canaisassoc.idSite_id, campanhas_canaisassoc.idCanal_id, campanhas_canaisassoc.ativo, campanhas_canais_dados.id, campanhas_canais_dados.nomeCanais, campanhas_canais_dados.ativo FROM campanhas_canaisassoc INNER JOIN campanhas_canais_dados ON (campanhas_canaisassoc.idCanal_id = campanhas_canais_dados.id) WHERE (campanhas_canaisassoc.ativo = True AND campanhas_canaisassoc.idSite_id = 3) If i run this in phpMyAdmin, they are working as expected, showing up all values i'm need it id|idSite_id|idCanal_id|ativo|id|nomeCanais|ativo However, if i inspect the call of JSON, they are returning this: {"channel": [{"model": "campanhas.canaisassoc", "pk": 14, "fields": {"idSite": 3, "idCanal": 13, "ativo": true}}, {"model": "campanhas.canaisassoc", "pk": 15, "fields": {"idSite": 3, "idCanal": 1, "ativo": true}}, {"model": "campanhas.canaisassoc", "pk": 16, "fields": {"idSite": 3, "idCanal": … -
Create Django objects in step increments
I'm trying to write a function to create total number of Django objects in step increments. Note, I'm using factory-boy to generate the fake data. Here is what I have come up with: def create_todos_in_batch(total, step): quotient, remainder = divmod(total, step) for i in range(quotient): print(f"Inserting {i * step:,} to {(i + 1) * step:,}") todos = TodoFactory.build_batch(step) Todo.objects.bulk_create(todos) if remainder: print(f"Inserting {total - remainder:,} to {total:,}") todos = TodoFactory.build_batch(remainder) Todo.objects.bulk_create(todos) To create 100 objects in 20 object increments, the function can be called like so: create_todos_in_batch(100, 20) I have the following unit test to prove this works correctly: @pytest.mark.parametrize( "total, step", [ (100, 20), (1_000, 100), (10_000, 1_000), ], ) @pytest.mark.django_db def test_create_in_batch(total, step): create_todos_in_batch(total=total, step=step) count = Todo.objects.count() assert count == total, f"{count:,} != {total:,}" Is there a better way to write this function? I feel like this is too verbose because I'm repeating TodoFactory.build_batch() and Todo.objects.bulk_create(todos) multiple times.