Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - makemigrations - No changes detected/Apps could not be found
I was trying to create migrations within an existing app using the makemigrations command but it outputs "No changes detected" The code I used for that is `python3 manage.py makemigrations` I tried python3 manage.py makemigrations polls and it shows "App 'polls' could not be found. Is it in INSTALLED_APPS?" Here is my INSTALLED_APPS of the settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls.apps.PollsConfig', ] I know some people simply put 'polls', it doesn't work either Here is my folder structure: File structure Here is my apps.py from django.apps import AppConfig class PollsConfig(AppConfig): name = 'polls I am using django2.1 and python3.8 -
Custom metrics from celery workers into prometheus
I have a few celery workers running in containers under kubernetes. They are not auto-scaled by celery and each run in a single process (i.e. no multiprocessing). I would like to get a bunch of different metrics from them into prometheus. I've looked at celery-prometheus-exporter (unmaintained) and celery-exporter but they are focused on metrics at celery level rather than app metrics inside of the celery workers. It looks like two options would be either to find some hacky way to get app level metrics to celery-prometheus-exporter which then would make them available to prometheus OR to use pushgateway. Which is better, or maybe there's another option I missed? -
Website not opening without www but opens with it
I am trying to deploy my website. It works fine with www but I get apache default page when I enter the website without www. I don't understand where the problem comes from, I have already set an Alias as you can see here. <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port t> # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. ServerName foot-bet.com ServerAlias www.foot-bet.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # … -
Does the following model design have optimization space?
Should port fields be of integer or string type? Should port fields use Boolean or enumeration types? (I'm not sure Django supports enumeration types yet) Or do you have any better suggestions? I would appreciate it if you could write specific code! from django.db import models class Proxy(models.Model) ip = models.GenericIPAddressField(protocol='IPv4') port = models.IntegerField() status = models.BooleanField() -
existe t'il une autre facon d'installer les requirement.txt dans un projets sans qu'il n'y ait pas d'erreur [closed]
je viens de cloner l'api d'un projet. J'ai bien suivit le fichier .README mais à chaque fois que je met pip install -r requirements.txt j'ai cette erreure suivanteenter image description here -
showing random users while excluding copies of the same user
I'm trying to display 3 random users on my home page. How would I go about doing that? I can get the users to display, but sometimes there are two of the same user that are showing. I want to make sure every time there are 3 unique users showing. views.py def home(request): random_profile1 = (Profile.objects.exclude(id=request.user.id).order_by('?')[0]) random_profile2 = (Profile.objects.exclude(id=request.user.id).order_by('?')[0]) random_profile3 = (Profile.objects.exclude(id=request.user.id).order_by('?')[0]) context = dict(random_profile1 = random_profile1, random_profile2 = random_profile2, random_profile3 = random_profile3) return render(request, 'dating_app/home.html',context) -
views still firing old function in django
Why is it everytime i fire the url for my logout view it still rendering the old function? but when i create one like example logout_test its rendering correct, is the browser cached my function in django? here is my urls.py: urlpatterns = [ path('', LoginView.as_view(), name = 'login'), path('logout/', logout, name = 'logout'), path('signup/', signup, name = 'signup'), ] here is my views.py: def logout(request): return test I put intentionally test in return so that i will expect an error, but still its rendering the old function which is: def logout(request): response = redirect(reverse_lazy('login:login')) return response -
pyodbc error: using django in docker container
I am using a docker container running django application. i get the below error whenever i try to run function that manipulates data on 2 separate databases error: [Microsoft][ODBC Driver 17 for SQL Server]SSL Provider: [error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol] (-1) (SQLDriverConnect)') this is the function i run def preStepBtn3(request): sourcePE = request.GET.get('sourcePE') targetPE = request.GET.get('targetPE') inputFTID = request.session['username'] datetime_object = datetime.datetime.now() step_name = "preStepBtn3" table_name = "null" Action_taken = "change router status to MIG" MassivePortalSessionID = request.session['MassivePortalSessionID'] try: with connections['DataAdmin'].cursor() as cursor: sql = """DECLARE @out nvarchar(max); exec DTA.mig_sop_ce_status2mig_django 0, %s, @param_out = @out OUTPUT; SELECT @out AS the_output; """ params = [sourcePE] cursor.execute(sql, params) rows = cursor.fetchall() result = [] result.append(rows) logDB_sql(MassivePortalSessionID, inputFTID, sourcePE, targetPE, table_name, step_name, datetime_object, Action_taken) print("data inserted in log DB") while rows: print(rows) if cursor.nextset(): result.append(cursor.fetchall()) else: print(result) return JsonResponse(result, safe=False) except Exception as ex: error = ex print(error) context = {'text': error} logDB_sql(MassivePortalSessionID, inputFTID, sourcePE, targetPE, table_name, step_name, datetime_object, Action_taken) print("data inserted in log DB during exception") return render(request, 'posts/textArea.html', context) whenever i remove the logDB_sql it works perfectly this is code for logDB_sql def logDB_sql(MassivePortalSessionID, inputFTID, sourcePE, targetPE, table_name, step_name, datetime_object, Action_taken): params = [MassivePortalSessionID, inputFTID, sourcePE, targetPE, table_name, step_name, datetime_object, Action_taken] print(targetPE) print(sourcePE) … -
Django keeps using wrong storage backend when trying to upload static files to S3
I have been using S3 as a storage service for other Django apps, however for a new project, Django refuses to pick up the correct backend and keeps putting the files on my local filesystem instead of upload. To be exact, after I install boto3 and adjust settings.py, then run python manage.py collectstatic, that command keeps moving the static files to <my_project_path>/staticfiles instead of starting the upload to S3. This is the output of python manage.py collectstatic: You have requested to collect static files at the destination location as specified in your settings: /Users/simon/projects/farmtokitchen/farmtokitchen/staticfiles This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: My settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # Vendor 'storages', 'allauth', 'allauth.account', 'allauth.socialaccount', 'sass_processor', 'crispy_forms', [..] ] # static & media files USE_S3 = config('USE_S3', cast=bool, default=True) AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_DEFAULT_ACL = None AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') if USE_S3: MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, 'media') DEFAULT_FILE_STORAGE = 'farmtokitchen.storage_backends.MediaStorage' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = … -
In Django how can I filter objects in a QuerySet based on a many to many relationship?
So I have a user Profile model with a data attribute which is a many to many field representing a Profile "friending" another Profile like on Facebook. Here's the code for that: friends = models.ManyToManyField("self") What kind of query can I do to write a method that gets me all the Profiles that are friends with a current Profile? friends = Profile.objects.filter(friends=self.pk) This seems to give an empty QuerySet when I test it. -
Cant pip-install mysql into venv on Mac OS Catalina for Django framework
Dears, I can not install mysql or mysqlclient into my venv. Everytime I try, I am getting this errors: However, I managed to brew-install it locally by using these steps: https://ruddra.com/posts/install-mysqlclient-macos/ It worked locally, but still, I can not create a proper venv with mysql or mysqlclient. I am using Django and PyCharm. Everytime I want to manage.py runserver, it asks me for mysqlclient. Error when trying to pip install mysql into my venv: Processing /Users/michaltarasiewicz/Library/Caches/pip/wheels/3e/4a/d0/506edab38d1bdf574b02c24805fcf7348a327297fcc285431d/mysql-0.0.2-py3-none-any.whl Collecting mysqlclient Using cached mysqlclient-1.4.6.tar.gz (85 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users/michaltarasiewicz/Projects/Venvs/Django/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/v5/rxvfdtj967bcph1hj69s0k8m0000gn/T/pip-install-v6y4fnwu/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/v5/rxvfdtj967bcph1hj69s0k8m0000gn/T/pip-install-v6y4fnwu/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/v5/rxvfdtj967bcph1hj69s0k8m0000gn/T/pip-wheel-8ds4c5v5 cwd: /private/var/folders/v5/rxvfdtj967bcph1hj69s0k8m0000gn/T/pip-install-v6y4fnwu/mysqlclient/ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.8 creating build/lib.macosx-10.9-x86_64-3.8/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb creating build/lib.macosx-10.9-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.9-x86_64-3.8/MySQLdb/constants … -
How can a django developer tell which code is the better one to use
I must say, I am really loving django and how the framework handles a lot of things, but sometimes, it just seems like there are way too many ways to do the same thing, that sometimes one just wants to know if a particular way is best. I have a filtering line of code that I initially wrote like this.. Post.objects.filter(author=user).filter(approved=True).order_by('-date_posted') I was going through my codes and just thought to change this line to Post.objects.filter(author=user, approved=True).order_by('-date_posted') I knew it would still work, but was still surprised it did the exact same thing. So, my question is, in a situation like this, how would one know which is the better implementation here? Cos both lines of code do filtering on the database level. -
Issue with Django interaction between user input + View + Html response
I am having an issue in my django project with the following logic: A user enters a value in a search bar (form ) that renders data on the same html page. He then can click on a data point that redirect the user on a new page where there is a table containing data regarding the value that he has originally entered. I am having a problem with the view that redirect the user from the original value entered, pass it in the table and shows him the data in the new html page. I don't know what is wrong with it. I hope someone can see where i am mistaken! view.py class PostSupplierData(APIView): def get(self, request): query = request.GET.get('search_ress', None) context = {} if query and request.method == 'GET': queryset = Item.objects.filter(fournisseur = query) table = SupplierData(queryset) context.update({'table' : table}) return render(request, 'SupplierData.html', context) table.py class SupplierData(tables.Table): class Meta: model = Item template_name = "django_tables2/bootstrap4.html" error: AssertionError at /SupplierData.html Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` I get that the error means that I am not actually rendering anything but I am not sure why that is. Please … -
Pandas Read CSV Byte Array from Multipart Request is altered
So i am trying to build a web time series analysis app for uni and i am stuck on a problem. The app is split in two services, a kotlin web service that will recieve a csv file from a client, encrypt and compress it (using GZIP, if it has any relevance) then storing the file into DB. When the client requests analysis on that specific file, it is retrieved from DB,decompressed and decrypted and sent to the python service via REST Multipart request as a byte stream to be consumed as a CSV. All good until there, when i look at the string representation of the file inside debug in the python service it seems good but somehow on the course the file has been altered and i cant find out why and where (because dataFrame.to_json() spits different results for the transferred file vs the original one). I can't find what i am doing wrong, should i Base64 encode the file before storing it to DB/sending it via REST? Thank you in advance! -
Django Markdownx Trouble
I am having trouble with markdown on my Django application. I am writing a blog from a tutorial, and want markdown in my posts. I installed Markdownx for Django, and it almost works. I have issues when it comes to code blocks. The markdown looks different in the admin page than it does in the rendering of the html page. I would like my code blocks to appear as they do on stackoverflow and github. Instead, when I do the code block formatting with the three ```, I get red text. Below are my files for the application I am asking about: project/urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('projects/', include('projects.urls')), path('blog/', include('blog.urls')), path('markdownx/', include('markdownx.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) project/settings.py ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projects', 'blog', 'markdownx', ] ... app/models.py from django.db import models from markdownx.models import MarkdownxField from markdownx.utils import markdownify class Projects(models.Model): title = models.CharField(max_length=100) short_description = models.TextField() long_description = MarkdownxField() project_link = models.URLField(max_length=250) def formatted_markdown(self): return markdownify(self.long_description) app/admin.py from django.contrib import admin from projects.models import Projects from markdownx.admin import MarkdownxModelAdmin class ProjectsAdmin(admin.ModelAdmin): pass admin.site.register(Projects, … -
'Profile object is not iterable'
So I'm having some difficulty here. I am attempting to match two users by checking if the user that the current user is voting on ALSO voted true to them. Now, it runs all way until it has to query the Profile objects, which is my user model since I created a custom user model. Now I'm stuck here because request.user should serve the Profile object, and it works in other parts of my code, but it's not working here. Furthermore, the code does create a 'vote' object regardless of wether or not the users get matched and put into my matches database. And the error only occurs if the other use has voted True on the current user, so that part is working, it's just not iterating through Profile objects. error error is at 'npm = Profile.objects.get(request.user)' traceback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 134, in nice return create_vote(request, profile_id, True) File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 157, in create_vote … -
"no user found" 404 on accounts/login using Django allauth
Aloha, I have been using allauth with my Django project since the start and have had no issues. Recently while trying to clean up some code and improve a user search feature it seems my changes break the accounts/login page. I have been unable to find any fixes online after 2 days of googling and searching through documentation and I am hoping someone with a little more experience might be able to see where my error is. I have narrowed the cause of the error to a change in a single URL in my users app, which is completely unrelated to allauth. When I change urlpatterns = [ .... path('<int:pk>/<str:slug>/', ProfilePageView.as_view(), name='profile'), path('search/', SearchResultsView.as_view(), name='search'), ] to urlpatterns = [ ... path('<str:slug>/', ProfilePageView.as_view(), name='profile'), path('search/', SearchResultsView.as_view(), name='search'), ] is when I receive the error. Inside my terminal I see Not Found: /accounts/login/ however in the browser I see No user found matching the query which confuses me because I am not sure where this query is coming from. The main change to my code that I am implementing is in my users.models def get_absolute_url(self): kwargs = { 'pk' : self.id, 'slug' : self.slug, } return reverse('users:profile', kwargs=kwargs['slug']) which is also … -
Rest API's with custom API Gateway
we have several Rest API's for different projects now that we are combining all the features in one product we need a gateway which should redirect the requests to certain servers. We are not going to using any already implemented solution like aws api-gateway etc. This gateway will also authenticate the requests. I've looked into several solutions and I've come up with one that I need acceptance from the experts on stackoverflow before I propose it to my boss. Create custom api-gateway using django-restframework [which itself will be a rest service]. Use JWT for authentication. Create apps with in the project for each service that will handle routing and requests. Now that I think about this, we will have to read each request in api-gateway and create another request body to pass it to a respective api. Is this a right approach? If not what other things i can look into or what changes i can make to this approach to make it work better and faster. below is the rough diagram I've created for your reference. -
DJANGO - Subtotal by category and total by item
Good evening ! Let's assume I have a database with : Category | Item | Price Cat1 | Item1 | $1 Cat1 | Item2 | $2 Cat2 | Item3 | $3 Cat2 | Item3 | $3 Cat2 | Item4 | $4 I would like to display the total sales by category and below the sales details group by items Cat1 - Total Price = $3 Item1 - $1 Item2 - $2 Cat2 - Total Price = $10 Item3 - $6 (the sum of the two item3) Item4 - $4 I almost succed but I don't know how to have the subtotal by category. My code below : Model.py class Category(models.Model): Category= models.CharField(max_length=100) class Item(models.Model): Category= models.ForeignKey(Category, on_delete=models.CASCADE) Item= models.CharField(max_length=100) class Order(models.Model): Category= models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) Item= models.ForeignKey(Item, on_delete=models.SET_NULL, null=True) Price= models.DecimalField() Views.py def summary(request): metrics = { 'total': Sum('Price'), } orders=Order.objects.values('Category','Item').annotate(**metrics)) Template.html {% for order in orders%} {% ifchanged order.Item%} <tr> <td>{{ order.Item}} </td> <td>{{order.total}} </td> </tr> {% endifchanged %} <tr> <td>{{order.Item}}</td> <td> {{order.total}}</td> </tr> {% endfor %} -
How do I stop Django Channels from killing my long-running view?
I have a Django project that uses Django Channels. Django version 2.2.10. Django Channels version 2.3.0. The app I'm working on at the moment does NOT use Django Channels - other apps in the same projects use it. The App I'm working on has a simple view: def generate_usage_report(request): time.sleep(300) return HttpResponse("Done") This view is being run by an AJAX request, so I don't care that it takes 5 minutes to return - the user's browser is showing a loading bar until it is done. Unfortunately, after about 30 seconds (give or take), I get this in my logs: WARNING Application instance <Task pending coro=<AsgiHandler.__call__() running at /opt/my_project/venv3/lib/python3.6/site-packages/channels/http.py:192> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/lib64/python3.6/asyncio/futures.py:403, <TaskWakeupMethWrapper object at 0x7f02891c44c8>()]>> for connection <WebRequest at 0x7f02891c20f0 method=GET uri=/my_requested_page clientproto=HTTP/1.0> took too long to shut down and was killed. And the Ajax call never completes, since the function call is killed prematurely. Is there some way to let it run until it completes? -
Django - TextInput Form for Each object in Many to Many relation
I have the following Django problem: I have 3 classes in Many to Many Person Person = models.ManyToManyField(CLASS 3, through='CLASS 2') IntermediateTable .. Person = models.ForeignKey(Person, on_delete=models.CASCADE) Vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) amount = models.IntegerField() Vehicle .. Vehicle = charfield(max_lenght=100) What i need is to have one textInput component in model Forms for each field in Vechicle Class, to set de amount field. For example if I have: Vehicles -> CAR - TRUCK - PLANE - SHIP Person1 has only ('CAR', 'TRUCK') but, when I'm creating that person I need 4 textInputs: CAR: 2 TRUCK: 1 PLANE: 0 SHIP: 0 and save it in intermediate table. Thanks! -
Why are my data values shifted by 24 hours only after 7pm?
I'm trying to query data from an unmanaged database in django. I'm trying to get the number of objects for every hour in a given day range. Ex. {'Hour': 18, 'Monday': 235, 'Tuesday': 0, 'Friday': 0, 'Wednesday': 0, 'Thursday': 0, 'Sunday': 163, 'Saturday': 0} {'Hour': 19, 'Monday': 127, 'Tuesday': 226, 'Friday': 0, 'Wednesday': 0, 'Thursday': 0, 'Sunday': 0, 'Saturday': 0} This dictionary represents all objects in the given hour on each day. The problem is that after 7pm, (hour 19), all of the values in the subsequent dictionaries should be shifted one day over. For example, in this dictionary: {'Hour': 19, 'Monday': 127, 'Tuesday': 226, 'Friday': 0, 'Wednesday': 0, 'Thursday': 0, 'Sunday': 0, 'Saturday': 0} The tuesday value should be in the monday entry, the monday should be in the sunday entry, etc. Here is my code for the query and dictionary population: #results filtered by appropriate gender and hour ordered_query = initial_query.annotate( Hour=ExtractHour('actualdatetime', tzinfo=eastern), ).values( 'Hour' ).annotate( Sunday=Coalesce(Sum(Case(When(actualdatetime__week_day=1, then=1)), output_field=IntegerField()), Value(0)), Monday=Coalesce(Sum(Case(When(actualdatetime__week_day=2, then=1)), output_field=IntegerField()), Value(0)), Tuesday=Coalesce(Sum(Case(When(actualdatetime__week_day=3, then=1)), output_field=IntegerField()), Value(0)), Wednesday=Coalesce(Sum(Case(When(actualdatetime__week_day=4, then=1)), output_field=IntegerField()), Value(0)), Thursday=Coalesce(Sum(Case(When(actualdatetime__week_day=5, then=1)), output_field=IntegerField()), Value(0)), Friday=Coalesce(Sum(Case(When(actualdatetime__week_day=6, then=1)), output_field=IntegerField()), Value(0)), Saturday=Coalesce(Sum(Case(When(actualdatetime__week_day=7, then=1)), output_field=IntegerField()), Value(0)), ).values( 'Hour', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ) #populate list of dictionaries … -
Django REST + filter/ Combining data on field X in django as an embedded response
iam use DJango Rest + Filter and now i have this api response { "symbol": "ZERO", "costs": "6.1391", "timestamp": "2020-04-08T14:15:55.765835Z" }, { "symbol": "ZERO", "costs": "6.1892", "timestamp": "2020-04-08T14:15:01.775659Z" }, { "symbol": "ZERO", "costs": "6.1221", "timestamp": "2020-04-08T14:13:49.217715Z" }, As you can see. I want to combine the timestamp and costs into an embedded response. To make it this way. That is, given the costs and timestamp for the every coin: {"symbol":"ZERO","costs":[ {"timestamp":"2019-12-14T00:00:07+00:00", "price":5.9505181}, {"timestamp":"2019-13-14T00:00:07+00:00", "price":5.915181}, {"timestamp":"2019-14-14T00:00:07+00:00", "price":6.915181} ]} serializers.py class CoinCostsSerializer(serializers.ModelSerializer): symbol = serializers.ReadOnlyField(source='coin_id.symbol') costs = serializers.CharField(source='price') class Meta: fields = ('symbol', 'costs', 'timestamp') model = CoinCosts views.py class CoinCostFilterSet(filters.FilterSet): class Meta: model = CoinCosts fields = { 'coin_id__symbol': ['exact'], 'timestamp': ['gt', 'lt'], } class CoinCostViewSet(viewsets.ModelViewSet): queryset = CoinCosts.objects.all() serializer_class = CoinCostsSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = CoinCostFilterSet How to do it? Thanks! -
How to change a Django model field argument dynamically
Given the model class Payments(models.Model): is_valid = models.BooleanField(blank=True) customer = models.ForeignKey('Customer', on_delete=models.CASCADE) ..... How can I add, remove and change the model field argument blank dynamically in my code ? I am writing unit tests (pytest) for a model heavy project, and want to remove the cumbersome effort of creating a mock record (more records if record has a foreign key) with many fields when only one or two are relevant for the test. -
How can I have a database with thousands of tables with varying number of columns that are all of the same class in Django / SQLAlchemy ORM?
I have financial statement data on thousands of different companies. Some of the companies have data only for 2019, but for some I have decade long data. Each company financial statement have its own table structured as follows with columns in bold: lineitem---2019---2018---2017 2...............1000....800.....600 3206...........700....300....-200 56.................50....100.....100 200...........1200......90.....700 This structure is preferred over more of a flat file structure like lineitem-year-amount since one query gives me the correct structure of the output for a financial statement table. lineitem is a foreignkey linking to the primary key of a mapping table with over 10,000 records. 3206 can for example mean "Debt to credit instituions". I also have a companyIndex table which has the company ID, company name, and table name. I am able to get the data into the database and make queries using sqlite3 in python, but advanced queries is somewhat of a challenge at times, not to mention that it can take a lot of time and not be very readable. I like the potential of using ORM in Django or SQLAlchemy. The ORM in SQLAlchemy seems to want me to know the name of the table I am about to create and want me to know how many columns …