Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM Subqueries
I'm trying to figure out how to perform the following SQL query with the Django ORM: SELECT main.A, main.B, main.C FROM (SELECT main.A, MAX(main.B) FROM main GROUP BY main.A) subq WHERE main.A = subq.A AND main.B = subq.B The last two lines are necessary because they recover the column C value when B is at a maximum in the group by. Without them, I would have A and the corresponding Max B but not the C value when B is at its max. I have searched extensively but cannot find an example that can construct this query using the Django ORM. Most examples use Django's Subquery class and show how to match the sub-queryset up with one column (so doing main.A = subq.A). But how do I match 2+ columns? -
Django Text box additional text issue
I am getting an extra text with a text box in Django. I wrote it initially for testing purpose but after even removing all lines "enter item number , this field is required" I am getting that with a text box.please check image for more clarity here and If I add any more Textboxes to my code by doing "ENTER= forms.IntegerField" I am getting "enter item number , this field is required" embedded over that textbox too. The code is as below:: forms.py from django import forms import re class InputForm(forms.Form): print("inside forms") regex = re.compile('^([1-9]{8})$', re.UNICODE) ENTER_ITEM_NUMBER= forms.RegexField(max_length=8, regex=regex,help_text=("Required 8 digits between {0-9}.")) input.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action = "{% url 'item'%}" method = "post"> {% csrf_token %} {{form}} <input type="submit" value=Submit" name="submitted"> </form> urls.py urlpatterns = [ path('inputs/', views.home_view, name='inputs'), path('item/', views.itemnumber, name='item'), ] views.py from django.db import connection from django.shortcuts import render from .forms import InputForm def home_view(request): context1 ={} context1['form'] = InputForm(request.POST) return render(request, "input.html", context1) def itemnumber(request): if (request.GET.get('submitted')): c = request.get['ENTER_ITEM_NUMBER'] cursor = connection.cursor() try: itemnumber = c C=cursor.execute(f"EXEC ValidateBusinessrule '0000000000{itemnumber}'") result_set = cursor.fetchall() result_set1= [' {} '.format(x) for x in result_set] context = {"row": result_set1} … -
Basic auth protected views in DRF
I have some API endpoints that i need to protect using HTTP Basic Authentication in Django Rest Framework. There is BasicAuthentication in DRF, but that actually authenticates against a user in Django, which is not what I'm looking for. I found a solution using a custom permission, but ti means monkey patching the views to set the correct authenticate header. Is there a better way? class BasicAuthPermission(permissions.BasePermission): def has_permission(self, request, view): credentials = view.credentials # Will raise AttributeError on missing credentials realm = getattr(view, 'realm', 'Protected') auth = request.headers.get('Authorization') with suppress(ValueError, AttributeError): auth = b64decode(auth.split()[-1]).decode() if auth != credentials: # Monkey patch style view.get_authenticate_header = lambda r: f'Basic realm="{realm}"' raise exceptions.AuthenticationFailed('Bad credentials.') return True Im my view: class ProtectedApiView(generics.GenericAPIView): permission_classes = [BasicAuthPermission] credentials = 'user:password' # ... -
Is there anything i missed in configuring django-rest-framework-datatables, getting error "DataTables warning: table id=test - Ajax error"
I tried to configure datatables with rest frame work, i'm getting error when page loads all the datatables fields like pagination, search and title is showing but no data is showing. what might be the reason? serializers.py class PermissionSerializer(serializers.ModelSerializer): class Meta: model = Permission fields = ( 'name', 'code', 'app', ) views.py from rest_framework import viewsets from .serializers import PermissionSerializer class PermissionViewSet(viewsets.ModelViewSet): queryset = Permission.objects.all() serializer_class = PermissionSerializer class ViewallPerms(View): def get(self, request): context = { 'a' : 'a', } return render(request, 'flamika_admin/view_allpermissions.html', context) urls.py url(r'^perms/$', views.PermissionViewSet, name='perms'), path('all-perms', login_required(views.ViewallPerms.as_view(), login_url='f_admin:admin_login'), name='all-perm'), view_allpermissions.html <script src="https://code.jquery.com/jquery-1.8.0.min.js"></script> <div class="row"> <div class="col-sm-12 col-xs-12"> <table id="test" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>Code</th> <th>Name</th> <th>App</th> </tr> </thead> </table> </div> </div> <script> $(document).ready(function() { var table = $('#test').DataTable({ "serverSide": true, dataSrc: "", "ajax": "{% url 'flamika_admin:perms' %}", "columns": [ {"data": "name"}, // Use dot notation to reference nested serializers. // This data: could alternatively be displayed with the serializer's ReadOnlyField as well, as seen in the minimal example. {"data": "code"}, {"data": "app"}, ] }); $('.btn-decade').on('click', function() { table.columns().search(''); var rel = $(this).attr('rel'); if (rel) { table.columns(3).search('^' + rel + '[0-9]$', true).draw(); } else { table.draw(); } }); $('#albums_minimal').DataTable({ "search": {"regex": true}, "language": {"searchPlaceholder": "regular expression"} … -
django.core.exceptions.ImproperlyConfigured: The included URLconf 'api.urls' does not appear to have any patterns in it
Having a hard time understanding why I am receiving this error. If I just leave the api/user/ path it works fine but when I try to add api/user/date_counter/ path I get this error. Using Django 3. Any help would be appreciated. date_counter/urls.py from django.urls import path from date_counter import views app_name = 'date_counter' urlpatterns = [ path('date_counter/', views.DateCounterViewSet.as_view(), name='date_counter'), ] date_counter/views.py from django.shortcuts import render from date_counter.models import Date_Counter from date_counter.serializers import DateCounterSerializer class DateCounterViewSet(viewsets.ModelViewSet): queryset = Date_Counter.objects.all() serializer_class = DateCounterSerializer date_counter/serializers.py from date_counter.models import Date_Counter from rest_framework import serializers class DateCounterSerializer(serializers.ModelSerializer): class meta: model = Date_Counter fields = ['user', 'date', 'count'] date_counter/models.py from django.db import models from user.models import User class Date_Counter(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) count = models.IntegerField(default=0) api/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/user/', include('user.urls')), path('api/user/date_counter/', include('date_counter.urls')), ] api/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'knox', 'user', 'date_counter', ] Stack Trace Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/urls/resolvers.py", line 590, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, … -
Deploy django app on linux shared hosting
I've made a django app and I'm ready to deploy it to a live server with my custom domain. The problem I'm facing is my I'm using a shared hosting and the terminal access is disabled by the administrator. SO is there any way to deploy django app successfully from cpanel. Thanks in advance. -
Django - oscar show a field in dashboard
from oscar.apps.catalogue.abstract_models import AbstractProduct from oscar.core.compat import AUTH_USER_MODEL from django.db import models class Product(AbstractProduct): seller = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) from oscar.apps.catalogue.models import * I added this code to forked catalog model > I want to show it in the dashboard,Image of dashboard and dropdown box I tried admin.site.register but it is not working. -
I am trying to use a locally hosted Django webserver's HTML button to execute a python script that's on my local machine and I'm stumped
So, I'm pretty new to Django, python, and javascript. I have a partially functional Django webserver that, while developing it, I host locally on my machine. I've made a button with HTML which I've figured out can be tied to a javascript script. The next step for me was to make this button "execute" a python script that's sitting on my machine, particularly on the /desktop directory. I can of course move the script though, but the important part is that I want that python script (let's call it django_test_script.py) to open its own window on my machine. It's just a file that says "hi" in stdout, then closes after 5 seconds, but due to the plan for this whole project, I want that to happen. I want to have my website open on my machine, click that button, then have the script's console pop up on my desktop and run/finish. The eventual goal is to control an LED strip that's plugged into my raspberry pi. I want colored buttons on the website that, when clicked, run appropriate python scripts that turn the lights to that color. It wouldn't take me long to write up the python scripts themselves that … -
Django - Customizing admin form element: modifying change_form to add jquery plugin
I appear to have a valid output when I view the page source on my customized django admin page. But I'm trying to add a jquery datetimepicker to the "Timeslot start" form element, and nothing happens when I click on it. No javascript error, nothing. Debug is True on my settings.py and there are no errors. change_form.html changes: {% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/forms.css" %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/schedule/jquery.datetimepicker.css' %}"/ > {% endblock %} . . . {% block admin_change_form_document_ready %} {{ block.super }} <script src="{% static 'js/jquery-3.2.1.min.js' %}"></script> <script src="{% static 'js/schedule/jquery.datetimepicker.full.min.js' %}"></script> <script type="text/javascript" id="django-admin-form-add-constants" src="{% static 'admin/js/change_form.js' %}" {% if adminform and add %} data-model-name="{{ opts.model_name }}" {% endif %}> jQuery(document).ready(function () { jQuery('#DTPicker').datetimepicker(); }); </script> {% endblock %} This is the page with the datetimepicker instructions, which I think I have followed correctly in this case. admin.py class TeacherAvailabilityAdmin(admin.ModelAdmin): form = TeacherAvailabilityAdminForm list_display = ('teacher_id', 'student_id', 'timeslot_start',) forms.py class TeacherAvailabilityAdminForm(forms.ModelForm): TEACHER_CHOICES_QUERYSET = TeacherProfile.objects.available_teachers() STUDENT_CHOICES_QUERYSET = StudentProfile.objects.active_students() teacher = forms.ModelChoiceField( queryset=TEACHER_CHOICES_QUERYSET, empty_label="Select One", to_field_name="id") student = forms.ModelChoiceField( queryset=STUDENT_CHOICES_QUERYSET, empty_label="Select One", to_field_name="id") timeslot_start = forms.DateTimeField(widget=forms.DateTimeInput(attrs={'id': 'DTPicker'}), required=True) class Meta: model = TeacherAvailability fields = ('teacher', 'student', 'timeslot_start') -
Need help to mash this code. I'm trying to copy a media file from someone and the DIR is messed up
I have media player I need to put on a site but, I don't know how to combine all this code in settings.py its throwing unrelated errors. STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'firegod/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__)) STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, '..', 'static'), ) MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') -
Using opencv to read a video file in Django, yet the cam won't open?
I am getting a video file from the user and storing it in the media folder. Then I pass a path to the file to a function, but when I use opencv to open the file, the cam won't open. start = time.time() cam = cv2.VideoCapture(video_name) fr = cam.get(cv2.CAP_PROP_FPS) The video_name is of the form /media/video_name.mp4 The error report is the following [ERROR:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap.cpp (116) cv::VideoCapture::open VIDEOIO(CV_IMAGES): raised OpenCV exception: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\videoio\src\cap_images.cpp:235: error: (-5:Bad argument) CAP_IMAGES: error, expected '0?[1-9][du]' pattern, got: /media/video_name.mp4 in function 'cv::icvExtractPattern' -
Pulling changed data from heroku
I have deployed a Django app in Heroku. I want the updated SQLite file to be reflected in my local repository. Is there any way I can do this. -
How to calculate total price using django?
I have simple django code, but it doesn't work. The code works to calculate total price from price and qty of the item purchased, then save it into the database. Here the code class Items(models.Model): items_name = models.CharField(max_length=50) harga = models.PositiveIntegerField() def __str__(self): return self.items_name class Transaction (models.Model): items = models.ForeignKey(Items, on_delete=models.CASCADE) qty = models.PositiveIntegerField() def total_price(self): total = self.qty * self.items.harga return total total_price = models.PositiveIntegerField(total_price) -
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.