Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Docker to create an offline version off a Django app
I'm a complete newbie to Docker and before pushing into further investigations, I wanted to assert that it is the proper tool for my needs. Here's the situation: I have to develop a Django app that will mostly be used online. But some users will sometimes need an offline use of this app. Then, back online, they will need to push there work to the main app. Can Docker help me to give these users a fully working offline version of the online app with very little work (from them, not me obviously...)? Thanks for the answers. -
Django MPTT - Nested checkbox in form / template
We are working on a django project that uses the MPTT package. It is a many to many relationship where you (as a company owner) can select services in a checkbox settingslist. What I am trying to get is a nested view (with checkboxes following the nodes) like so: Node1 ----subnode1 ----subnode2 Node2 ----subnode3 ----subnode4 We have it setup like this in our admin view. (With the feincms package). I tried using the 'FancyTree' package to set it up like this in our 'frontend'. But it used libraries such as 'MergeDict' that are no longer supported by Django. We currently have a working form (using a modelform with a 'CheckSelectMultiple' field). This it great in the sense that it works and that it makes all of the somewhat complicated 'manytomany' relationships easy to handle, but the checkboxes in the form are not nested. Node1 subnode1 subnode2 Node2 subnode3 subnode4 So I created a custom HTML page with the form as it should appear <form action="." method="POST" class="post-form">{% csrf_token %} <ul> {% recursetree facetten %} <li> <label><input type="checkbox" name='facet' value={{ node.pk }}><h3>{{ node.name }}</h3></label> {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree … -
PostgreSQL table partionning in Django
I have a PostgreSQL 9.6 database and I've split one of tables in multiple partitions using the client_id field. Now I'm trying to change the application to use those partitions more efficient, especially for the INSERTs, UPDATEs and DELETEs. I'm doing a lot of UPDATEs and INSERTs and using a trigger on the parent table has a performance impact. The table has around 800 million rows. I created a new Manager and QuerySet for that specific table. class IllegallinkInstanceQuerySet(models.query.QuerySet): def filter(self, *args, **kwargs): partition_field = getattr(self.model, self.model.PARTITION_FIELD, None) if partition_field and partition_field.field.attname in kwargs: client_id = kwargs[partition_field.field.attname] self.model._meta.db_table = self.model.get_child_table_name(client_id) self.query.model = self.model return super(IllegallinkInstanceQuerySet, self).filter(*args, **kwargs) class IllegallinkInstanceManager(models.Manager): def get_queryset(self): return IllegallinkInstanceQuerySet(self.model, using=self._db) class IllegalLinkInstance(models.Model): PARTITION_FIELD = 'client' objects = IllegallinkInstanceManager() ... For UPDATESs that are per Object/row is pretty easy because I can override the save method of the Model. For batch UPDATEs, DELETEs is more complicated because I need to change the QuerySet. My idea is to change the db_table field in the Meta class of the Model with the wanted table partition name before applying the filters. This works when building the first query the second one breaks. For example: print(IllegalLinkInstance.objects.filter(client_id=600).query) prints: SELECT "illegallinkinstance_fkclientid$i_500_707"."id", "illegallinkinstance_fkclientid$i_500_707"."fkclientid" FROM … -
How works WSGIScriptAlias with non root route?
I am running a Django app with Apache 2.2 and my WSGIScriptAlias in virtualhost file looks like: WSGIScriptAlias /site /var/www/site/app/wsgi.py So when I go to http://ip/site it shows a form with action="./#submit" and I hit the Submit button then browser goes to http://ip/ and my app is not running there. I did not develope the Django app, but when WSGIScriptAlias is WSGIScriptAlias / /var/www/site/app/wsgi.py, everything works great. Thanks in advance -
How to add client side hashing (using JS) in a Django project
How can I add a client side Javascript hashing function? I have created this function : <script type = "text/javascript"> function myHash(){ var password = document.getElementById("password") var hash = ''; for(i=0;i<password.length;i++){ var temp = password.charAt(i).charCodeAt(0); temp = Math.pow(temp,5)%14; hash += String.fromCharCode(temp); } return hash; } </script> Put this file in polls/static/polls folder. Following is the HTML form : <HTML> <HEADER> {% load static %} <script type="text/javascript src = '{% static 'hashing.js' %}'"></script> <link rel="stylesheet" href="../../static/css/css.css"> <TITLE>LOGIN</TITLE> <h1>POLLING APP</h1> </HEADER> <BODY> <h1>USER LOGIN :-</h1> <br /> <br /> <br /> <FORM id="login_form" method="post" action="/login/user_login/" onsubmit="return myHash()"> {% csrf_token %} Username: <input type="text" name="username" value="" id="username" size="50" /> <br /> <br /> Password: <input type="password" name="password" value="" id="password" size="50" /> <br /> <br /> <INPUT type="submit" name="submit" value="submit"/> </FORM> </BODY> </HTML> The polls/views.py file is as follows : from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from .models import Question, Choice from django.urls import reverse from django.template import RequestContext from django.contrib.auth import authenticate, login, logout #from django.template import loader #def index(request): # return HttpResponse("Hello world! you are at the polls index") # Create your views here. def index(request): print(request.user) latest_question_list = Question.objects.order_by('-pub_date')#[:5] # template=loader.get_template('polls/index.html' context={'latest_question_list':latest_question_list} return render(request,'polls/index.html',context) def detail(request, question_id): … -
Django login redirection
I'm working on two differents apps I created called ticket and money. I would like that after the login, user who's staff (user.is_staff) could be redirect to the homepage of money app (money_homepage) and user who's not staff redirect to the homepage of ticket (ticket_homepage). I already looked for the function login in contrib/auth/views.py and in registration/login.html : <input type="hidden" name="next" value="{% if next %} {{ next }} {% else %} ../{% endif %}"/> But I didn't find my answer yet. Can someone help me ? Thanks. -
dynamic Backgrounds for django using image upload
I've looked around and haven't found a satisfactory solution. I am trying to uploaded an image via the Django admin interface using models and then call that uploaded image to be used as the background for a div .i.e - I create football called Salford City, I upload a picture of the team. I will have several teams. If I choose Salford then the background changes, if I choose Brighton Albion then the background changes. I have it working using javascript and hard coded cities but I would like to be able to do it dynamically without have to change base coding to enable easy scaling. Current code is as follows: Models.py: class City(models.Model): index = models.CharField(unique=True, max_length=250, null=False, blank = False, verbose_name = 'City Inner Search Name(lowercase)') landing_page_description = models.CharField(max_length=5000, null=True, blank = True, verbose_name = 'City Description') name = models.CharField(max_length=250, null=False, blank = False, verbose_name = 'City Common Name') country = models.ForeignKey(Country, null=True, blank=True) image = models.ImageField(upload_to="images/", blank=True, null=True, verbose_name= 'City Image') The images are stored in media_files/images The html: <div id="main" class="container-fluid citybackground"> <!-- <img src="{{ MEDIA_URL}}{{ City.image.url }}"> --> AS you can see I tried multiple options. The commented out section was a method I tried. … -
Django-smart-selects: Don't see values in 'Country' field
I tried to use django-smart-select.(ChainedForeignKey). But template doesn't display values of No Errors, but I can't see list of values in field country. Country field picture: Maybe I add wrong attributes in ChainedForeignKey(), I don't understand=( Please, help me to fix it. Thanks Models.py: from smart_selects.db_fields import ChainedForeignKey class ListOfContinents(models.Model): id_Continent = models.AutoField(primary_key=True) Continent = models.CharField(max_length=200,unique=True) def __str__(self): return '%s' % self.Continent class ListOfCountries(models.Model): id_Country = models.AutoField(primary_key=True) Continent = models.ForeignKey( ListOfContinents, default=0, to_field='Continent',db_column='Continent') Country=models.CharField(max_length=200,unique=True) def __str__(self): return '%s' % self.Country class Location(models.Model): Continent=models.ForeignKey( ListOfContinents,to_field='Continent', db_column='Continent',verbose_name='Континент',null=True) Country = ChainedForeignKey(ListOfCountries,chained_field="Continent", chained_model_field="Continent", show_all=False, auto_choose=True, sort=True, verbose_name='Страна', db_column='Country', to_field='Country', null=True) Forms.py: class LocationForm (forms.ModelForm): class Meta: model = Location fields = ('Continent','Country') Templates.py: <form method="POST" class="post-form">{% csrf_token %} {{ form_add.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> view: def Loc(request): if request.method == "POST": form_add = LocationForm(request.POST) if form_add.is_valid(): Loc.save() return redirect('Loc_edit_full') else: form_add = LocationForm() return render(request, 'utest_base/Loc_add.html', {'form_add': form_add}) -
Capitalized zip code field
I have defined a field in Django zip_code = models.CharField(_('Zip code'), max_length=19, blank=True, null=True) In the moment, I need that each letter to be capitalized for that field. I use this field in formlayout.py file : Row( Column('city', css_class="s12 m5"), Column('state', css_class="s12 m5"), Column('zip_code', css_class="s12 m2"), ), How could I capitalize zip_code here? Could I create a @property method in which I will transform this field? What is the best place to put this method? utils.py? views.py? models.py? -
Django Search Function inside ForeignKey
I have a class with huge of data and another class wich should take title from this class. How can i add a Search function to ForeignKey as you can see on following Image. Or maybe have a django another way to solve this "problem"? Thansk! Search inside ForeignKey class Menue(models.Model): title = models.CharField(max_length=255) panels = [ FieldPanel('title', classname="col12"), ] def __str__(self): return self.title class Wochen(models.Model): menu_1 = models.ForeignKey(Menue, null=True, blank=True, on_delete=models.PROTECT, related_name="menu_1+") panels = [ FieldPanel('menu_1', classname="col12"), ] def __str__(self): return self.menu_1 -
I hava image field error in django
I created a django app and I write this to its models file: from django.db import models from ckeditor.fields import RichTextField from django.template.defaultfilters import slugify class article(models.Model): title=models.CharField(max_length=120,verbose_name="Title") summary=models.TextField(verbose_name="Summary", blank=True, null=True) content=RichTextField(verbose_name="Content") pub_date=models.DateTimeField(auto_now_add=True, verbose_name="Date/Time") image=models.ImageField(blank=True, null=True) slug=models.SlugField(unique=True) def owntitle(self): return self.title and this admin file: from django.contrib import admin from .models import article class articleadmin(admin.ModelAdmin): list_display = ('title','pub_date','slug') search_fields = ('title','content','summary' ) prepopulated_fields = {'slug': ('title', )} admin.site.register(article, articleadmin) also I install pillow lib. when I create an article with imagefield its says this: expected str, bytes or os.PathLike object, not list -
How to add a directory in Django for Download link ?
I have developed a data science web app that generates various statistical analysis related graphs. Statistical functions being executed from the Django app called "ProtocolApp", where I have a directory as "Statistical_protocols" while the "Stat_Learning" project is the base directory. My programme is generating some image files and .csv output file withing the base directory of project "Stat_Learning", Same directory where "manage.py" is present". Within a template i have provided link for all the file like this: Template: {% extends 'protocol/base.html' %} {% load static %} {% block content %} <style type="text/css"> table { margin-bottom: 20px; border-collapse: collapse; border-spacing: 0; width: 30%; border: 1px solid #ddd; bgcolor: #00FF00; } th, td { border: none; text-align: left; padding: 8px; } tr:nth-child(even){background-color: #f2f2f2} </style> <div style="overflow-x:auto;"> <table align="center"> <tr> <th align="center">Result files</th> </tr> {% for a in names %} <tr> {% if a %} <td><a href="/virtual_env_dir/Base_rectory_of_the_project/{{a}}"> {{a}} </a> <br></td> {% endif %} </tr> {% endfor %} </table> </div> {% endblock %} Is there a method to provide downloadable link through this base directory for all the files. or is there any method to add another directory called "Downloads" others then media directory. Because I am using media directory to upload the input … -
Getting Started with Django Channels - WebSocket network error: kCFErrorDomainCFNetwork 2
I am trying to learn Django channels in accordance with Getting Started with Django Channels. In my Django code I did everything as is described on this page, however I have a problem with this part: Let’s test it! Run runserver, open a browser, navigate to a page on the server (you can’t use any page’s console because of origin restrictions), and put the following into the JavaScript console to open a WebSocket and send some data down it (you might need to change the socket address if you’re using a development VM or similar) // Note that the path doesn't matter for routing; any WebSocket // connection gets bumped over to WebSocket consumers socket = new WebSocket("ws://" + window.location.host + "/chat/"); socket.onmessage = function(e) { alert(e.data); } socket.onopen = function() { socket.send("hello world"); } // Call onopen directly if socket is already open if (socket.readyState == WebSocket.OPEN) socket.onopen(); I start server, open http://localhost:8000 and press option + command + c (console). Then I paste my source code shown above and I get: WebSocket network error:(Error kCFErrorDomainCFNetwork 2.) Any suggestions what is wrong? -
Tracking unique users hitting certain urls in Django project
In a Django project of mine, I want to log all unique user IDs visiting a certain section of the web application. Currently, the only distinguishing feature of this section is that it's url patterns are written in a separate module. What would be the best way to track unique users who visit these url patterns? Doing it as costlessly (resources wise) as possible is what I mean by 'best'. An illustrative example would be great. -
Problems with API call in Django application
I am making a simple API call in a Django application but I'm having some issues Here is the ajax call: $.ajax({ type: "GET", url: "/query/", success: function (data) { alert(data); } }); Here is the function calling the API: def query(request): response = requests.get("http://api.open-notify.org/iss-now.json") return JsonResponse(response.status_code, safe=False) This only works every other time it is triggered, one failure then one success. There is no exception captured when it fails. Below is what is displayed in the output window after a failure. The thread 0x2008 has exited with code 0 (0x0). File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Program Files\Python36\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [27/Jul/2017 13:56:15] "GET /query/ HTTP/1.1" 500 59 Exception happened during processing of request from ('127.0.0.1', 56126) Traceback (most recent call last): File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Program Files\Python36\lib\wsgiref\handlers.py", line … -
Django Facebook login with django's logout. Unable to re-login
I'm using social-auth-app-django as social authentication with my django app. It's going so good so far... User can login Can display username User can Logout using auth_views.logout. And there is the problem. User cannot log back in. I think Django's auth_views.logout is causing the problem. Any suggestions? -
Setup Staticfiles for Django in Heroku
I have deoployed a Django project in Heroku.It works fine but no staticfiles are worked.Anyone help me to setup staticfiles in Heroku for Django ? My Project Structure. src|---myproject | |----settings |----myapp |----static |----static-files | |----static-root | |----media-root |----templates settings/init.py from .base import * from .production import * try: from .local import * except: pass settings/base.py https://pastebin.com/xULz52r0 settings/production.py https://pastebin.com/Spk59Gxh settings/local.py https://pastebin.com/2XWWfXt6 wsgi.py https://pastebin.com/cY4uqg1z urls.py https://pastebin.com/Jy5wXFzS -
Why would form validation removes a simple string?
I'm having trouble when trying to validate a basic ModelForm instanciated with a QueryDict. The form has a field 'name' and when it goes through form.cleaned_data its value is removed, even when I submit something like "abc" as name. Consequently, I cant validate the form. I'm a bit used to Django and it's the first time I face such an issue. Below are the corresponding lines in my view. elif elem_type == 'AP': form = ApplicabiliteForm(QueryDict(request.POST.get('form')), prefix='AP') What is actually weird is that I can see "abc" in form['data'], I've already checked if it wasnt a problem of min/max_length or this kind of thing. Moreover, when I try ApplicabiliteForm(QueryDict(request.POST.get('form')), prefix='AP').is_valid() in debugger it returns true. Any help will be appreciated, it's actually blowing my mind ! Thanks in advance. -
get month grouped in django QRM
As of now i have tried extracting month details using total_dict= MyModel.objects.values('Gender', 'DOJ').annotate(count=Count('Gender')).order_by('DOJ', 'Months') for d in total_dict: d['DOJ']=str(d['DOJ'].month) print total_dict output is: [{'DOJ': '1', 'Gender': u'Male', 'value': 1}, {'DOJ': '1', 'Gender': u'Male', 'value': 1}, {'DOJ': '1', 'Gender': u'Female', 'value': 1}] extracting months from DOJ datefield. What i want is Male together be in one list i.e {'DOJ': '1', 'Gender': u'Male', 'value': 1}, {'DOJ': '1', 'Gender': u'Male', 'value': 1} be as {'DOJ': '1', 'Gender': u'Male', 'value': 2} -
Data Integration Between JS and Python in Django with Ajax
I need to understand a simple call with ajax from JS to Python .I have a python function .This function take a simple parameter and return a result . I want to send this parameter from js ,and get function result to js . I try as below .Python function is ok ,but js side i know i made some wrongs . Here is my python code , function.py : from suds.client import Client as Client def get_result_by_code(promocode): url="http://service.emobile.az:8080/ws-loyalty- program/cp/loyaltyprogram.wsdl" client = Client(url) result = client.service.loyaltyProgramCalculate( amount=1000, authKey='TEST6aede35740f2b9d2248b0ab6b878', identicalCode=promocode, terminalCode=2166) if str(result[2])=="SUCCESS": status = 1 else: status = 0 return status This function return 1 or 0 with promocode . And my javascript function is below. I know this function is wrong and need to fix: function get_result_by_code() { promocode = $('#bakcelPromo').val(); $.ajax({ type: "GET", url: "\docflow\projects\modules_2", dataType: "json", async: true, data: {"promocode": promocode}, succes: function (json) { $('#output').html(json.message); } }); } And last calculation function in js that will be played on screen is : function calculate() { if ( get_result_by_code.val() == 1 ) calculated_premium = calculated_premium * 0.2 else calculated_premium = calculated_premium calculated_premium = Math.ceil(calculated_premium) -
Connect Django app with Elasticsearch using Haystak
I am creating a Django app that has millions of data in it. So, for better result I am using trying to use Elasticsearch to store the data. I am also trying to use Haystack for search process. But currently I am stuck in the process of connecting the Django app with Elasticsearch through Haystack. My database configuration is: 'default': { 'ENGINE': 'django_elasticsearch', 'NAME': 'test', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '9200', 'SUPPORTS_TRANSACTIONS': False, }, In the settings.py file I have haystack and elasticsearch app installed. Also I have copied Haystack setting as per the documentation in settings.py. HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch2_backend.Elasticsearch2SearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack', }, } The elasticsearch runs perfectly { "name" : "TN1nVS-", "cluster_name" : "elasticsearch_manishojha", "cluster_uuid" : "zZQxFpkCT8qUO_GVVQAmHA", "version" : { "number" : "5.5.1", "build_hash" : "19c13d0", "build_date" : "2017-07-18T20:44:24.823Z", "build_snapshot" : false, "lucene_version" : "6.6.0" }, "tagline" : "You Know, for Search" } Now all that is required is the connection between the application and elasticsearch. -
Graphite web blank screen
I've installed graphite 1.0.1 release by chef cookbook (https://github.com/sous-chefs/graphite) with Django 1.8.18 (tried 1.9.X version too) with nginx as web server backend and after successfull installation I see only top bar. Looks like static content didn't load. Where I made a mistake? enter image description here -
why python migration renamed tables?
Im just new in python django... i was creating some models like this: class Question(models.Model): question_text=models.CharField(max_length=200) pub_date=models.DateTimeField("DatePublished") class Choice(models.Model): question=models.ForeignKey(Question,on_delete=models.CASCADE ) choise_text=models.CharField(max_length=200) votes=models.IntegerField(default=0) class Question(models.Model): question_text=models.CharField(max_length=200) pub_date=models.DateTimeField("DatePublished") class Choice(models.Model): question=models.ForeignKey(Question,on_delete=models.CASCADE ) choise_text=models.CharField(max_length=200) votes=models.IntegerField(default=0) and ran this two commands in pycharm terminal: python manage.py makemigrations polls python manage.py sqlmigrate polls 0001 then i saw some outputs like this:`BEGIN; -- -- Create model Choice -- CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choise_text" varchar(200) NOT NULL, "votes" integer N OT NULL); -- -- Create model Question -- CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" da tetime NOT NULL); -- -- Add field question to choice -- ALTER TABLE "polls_choice" RENAME TO "polls_choice__old"; CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choise_text" varchar(200) NOT NULL, "votes" integer N OT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id")); INSERT INTO "polls_choice" ("choise_text", "id", "question_id", "votes") SELECT "choise_text", "id", NULL, "votes" FROM "polls_choic e__old"; DROP TABLE "polls_choice__old"; CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id"); COMMIT; ` like you see it renamed table named polls_choice to polls_choice_old! but why? it means maybe there was some table by the same name in database !! Ok, … -
show detailed view of detailed view django
I am build a guide website. Each guide is made of steps. Each step is made of tasks. So to go the the next step you need to complete the task and then you will go to the next step until there is no more steps. Then you have completed the guide. I want the urls to be like this /1/3/6 (guide1/step3/task6) I have issues to create views to show this. I need help. Here is my code: Urls.py for app urlpatterns = [ url(r'(?P<guide_id>[0-9]+)/$', views.taskoftheday, name="taskoftheday"), url(r'(?P<guide_id>[0-9]+)/(?P<step.sequence_num>[0-9]+)/$', views.taskoftheday_step, name="taskoftheday_step"), url(r'(?P<guide_id>[0-9]+)/(?P<step.sequence_num>[0-9]+)/(?P<task.sequence_num>[0-9]+)/$', views.taskoftheday_task, name="taskoftheday_task"), ] urls.py for project urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('registration.urls')), url(r'^taskoftheday/', include('taskoftheday.urls')), url(r'^', include('taskoftheday.urls')), url(r'^analytics/', include('analytics.urls')), url(r'^progress/', include('progress.urls')), url(r'^goals/', include('goals.urls')), url(r'^registration/', include('registration.urls')), url(r'thanks/', views.thanks), url(r'thanks_again/', views.thanks_again), url(r'^$', views.landing_page), ] models.py class Guide(models.Model): name = models.CharField(max_length=200) guide_category = models.CharField(max_length=70) guide_why = models.TextField() guide_how = models.TextField() is_complete = models.BooleanField(default=False) def __unicode__(self): return self.name class Step(models.Model): guide = models.ForeignKey(Guide, on_delete=models.CASCADE) sequence_number = models.PositiveIntegerField(default=1) name = models.CharField(max_length=10) is_complete = models.BooleanField(default=False) class Meta: unique_together = ("guide", "sequence_number") def __unicode__(self): return self.name class Task(models.Model): step = models.ForeignKey(Step, on_delete=models.CASCADE) sequence_number = models.PositiveIntegerField(default=1) name = models.CharField(max_length=10) task_img = models.ImageField() task_task = models.TextField() task_description = models.TextField() is_complete = models.BooleanField(default=False) class Meta: unique_together = ("step", "sequence_number") … -
Should I do my update in the database or in Python?
"It's best to do the heavy lifting in the database." I'd heard that and seen it written many times. WOW was that wrong! This tiny little writeup chronicles what was actually a major breakthrough in my product's development. My original question on SO was how to efficiently link my records. Some of you guys really helped out! Here's what I found. Your situation might be different! Your app tracks the ownership of cars, and correlates data to them. Here are some models: # There are ~2M OwnershipRecord models class OwnershipRecord(models.Model): vin = models.CharField(...) saledate = models.DateField(...) active = models.BooleanField(...) # There are ~1M MaintenanceRecord models class MaintenanceRecord(models.Model): vin = models.CharField(...) ownership_record = models.ForeignKey(OwnershipRecord, ...) mileage = models.DecimalField(...) date_in_shop = models.DateField(...) So how to link these records? We care about the date and the vin, right? For example, if a car was: Sold on 1 June Maintenance was performed on 12 May Maintenance was performed on 15 July Then those MaintenanceRecords link to two separate OwnershipRecords. You can see how this would be an intensive task. There are a few different approaches to linking that I tried. Offload each new maintenance record to Celery. Use query to find the right OwnershipRecord …