Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djnago and Celery error: [Errno 111] Connection refused,
I am using python 2.7 and Django 1.11.4,to send an Email whenever an order is placed, but i don't know why does Celery through this error [Errno 111] whenever a task is triggered ? my celery.py (which is next to my settings.py file) from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings') app = Celery('myshop') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) my init.py, in the same directory level . from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] my task.py , which is inside my order application . from celery import task from django.core.mail import send_mail from .models import Order @task def order_created(order_id): """ Task to send an e-mail notification when an order is successfully created. """ order = Order.objects.get(id=order_id) subject = 'Order nr. {}'.format(order.id) message = 'Dear {},\n\nYou have successfully placed an order. Your order id is {}.'.format(order.first_name, order.id) mail_sent = send_mail(subject, message, 'admin@myshop.com', [order.email]) return mail_sent orders.views.py from future import unicode_literals from django.shortcuts import render from .models import OrderItem from .forms import OrderCreateForm from .tasks import order_created from cart.cart import Cart def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in … -
IndexError: list index out of range: I can uderstand why this error happens
I got an error IndexError: list index out of range. I wanna put dictionary data to the model(User) . I wrote book2 = xlrd.open_workbook('./data/excel1.xlsx') sheet2 = book2.sheet_by_index(0) for row_index in range(1,sheet2.nrows): rows = sheet2.row_values(row_index) print(rows) user3 = User.objects.filter(user_id=rows[0]) if user3: user3.update(talk1=rows[2],characteristic1=rows[3],talk2=rows[4],characteristic2=rows[5], talk3=rows[6], characteristic3=rows[7],talk4=rows[8], characteristic4=rows[9], talk5=rows[10], characteristic5=rows[11],talk6=rows[12], characteristic6=rows[13], talk7=rows[14], characteristic7=rows[15], talk8=rows[16], characteristic8=rows[17]) However,the number of rows's index is different from each list.rows is like ['001200cd3eF', 'Tom', 'Hi', 'greeting', 'Goodmorning', 'greeting', 'Bye' 'say good‐bye', '', '', '']['007700ab7Ws', 'Blear', 'How are you', 'greeting', 'Thx', 'Thanks', '', '', ''] so each list's the number of index is different,max index is 13. models.py is Class User(models.Model): talk1 = models.CharField(max_length=500,null=True) talk2 = models.CharField(max_length=500, null=True) talk3 = models.CharField(max_length=500, null=True) talk4 = models.CharField(max_length=500, null=True) talk5 = models.CharField(max_length=500, null=True) talk6 = models.CharField(max_length=500, null=True) talk7 = models.CharField(max_length=500, null=True) talk8 = models.CharField(max_length=500, null=True) characteristic1 = models.CharField(max_length=500,null=True) characteristic2 = models.CharField(max_length=500, null=True) characteristic3 = models.CharField(max_length=500, null=True) characteristic4 = models.CharField(max_length=500, null=True) characteristic5 = models.CharField(max_length=500, null=True) characteristic6 = models.CharField(max_length=500, null=True) characteristic7 = models.CharField(max_length=500, null=True) characteristic8 = models.CharField(max_length=500, null=True) I wanna put null if a list does not have value.How should I fix this?What should I write it? -
Django models.DateTimeField django.db.utils.IntegrityError: NOT NULL constraint failed
What is the problem? I have googled and have not found any thing that gets close to what I have. Saving the profile to then continue to the next page produces the error. I am working on the development server using sqlite. Thank you. models.py class SchoolProfile(models.Model): create_date = models.DateTimeField( null=False, blank=False, verbose_name=u'Fecha de creación') modification_date = models.DateTimeField( null=False, blank=False, verbose_name=u'Fecha de última modificación') cycle = models.CharField( null=False, blank=False, max_length=9, verbose_name='Ciclo escolar') name = models.CharField( null=False, blank=False, max_length=100, verbose_name='Nombre de la escuela') def __unicode__(self): return '{} {}'.format(self.cycle, self.name) class Meta: db_table = 'Perfil Escolar' ordering = ['id', 'name'] verbose_name = 'Perfil Escolar' verbose_name_plural = 'Perfiles Escolares' class Admin: pass class SchoolServices(models.Model): school_profile = models.ForeignKey( SchoolProfile, on_delete=models.CASCADE) tipo = models.IntegerField( choices=SCHOOL_TYPE_CHOICES, default=SCHOOL_TYPE_KINDER, verbose_name='Tipo de Escuela') folio = models.CharField( null=True, blank=True, max_length=40, verbose_name='Folio') def __unicode__(self): return '{} [{}]'.format(self.tipo, self.folio) class Meta: db_table = 'Servicio Escolar' ordering = ['tipo', 'folio'] verbose_name = 'Servicio Escolar' verbose_name_plural = 'Servicios Escolares' class Admin: pass forms.py class SchoolProfileForm(ModelForm): class Meta: model = SchoolProfile readonly_fields = ( 'create_date', 'modification_date',) fields = ( 'cycle', 'name',) class SchoolServicesForm(ModelForm): class Meta: model = SchoolServices fields = ( 'tipo', 'folio',) views.py class SchoolProfileView(LoginRequiredMixin, CreateView): model = SchoolProfile form_class = SchoolProfileForm context_object_name = … -
How to create a new model (kind) in google cloud Datastore
I am using Google Cloud Datastore(not NDB) for my project. python2.7 and Django. I want to create a new model, lets say Tag model. class Tag(db.Model): name = ndb.StringProperty() feature = ndb.StringProperty(default='') I have added property to a model many times, but not yet created new model. My question is when I have changed model schema in Django for my another project using mySQL, I always executed manage.py migrate. Do I have to execute the migration command for Datastore as well? Or just defining the model is all I have to do? Thanks in advance! -
Django - Sending email works in shell, but not on localhost - ConnectionRefusedError
I'm new to Django, but I have read on the order of 50 pages (mostly SO and Django documentation) and haven't found anything that quite works for my situation. I'm merely trying to send an email via the send_mail function in Django; although I'm hoping to get this working through SMTP on Gmail, right now it doesn't even work via localhost. When I run my test_email.py file where I'm testing this send_mail function, I get the following error: ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it When I run this same send_mail call in the shell (via python manage.py shell), it's completely fine and displays the email just as I would expect. It's only once I try to run it in Django that the error pops up. Note that I get the above error no matter which permutation of the following 2 sets of settings I put in my settings.py file: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False I've also played around with the following in my settings.py file, and various mixes of these settings with the previous set (though I guess … -
Django: User Reporting Some URL on Website
So i'm trying to build something, so that users would be able to report something on site. Here's the model, class Report(models.Model): reporting_url = models.URLField() message = models.TextField() I created Form for this Model including 'message' field only because 'reporting_url' is something it needs to populate by itself depending upon the specific page from where user has clicked "Report" button. def report(request): url_report = ??? if request.method == 'POST': form = ReportForm(request.POST or None) if form.is_valid(): new_form = form.save(commit=False) new_form.reporting_url = url_report new_form.save() I was wondering How can I pass the specific url to 'reporting_url' field in form depending on the Page from where user has clicked "Report" button? (Much like s we see on social Networks). Am I doing this correctly, Or is there a better way for doing this? Please help me with this code. Thanks in Advance! -
Can I use Python to create a website, which can downloadable generate PDF file?
I am going to create a website, from which people can download the PDF file. I know there are a lot of frameworks, such as Django, Hexo, but not sure which one should I use. Also, can I do all these things (website construction, PDF download function) only in Python? Thank you very much for your help! -
Django no module named elasticsearch_dsl.connections
I'm trying to connect my Django model to the Elasticsearch server on local host but when I try from elasticsearch_dsl.connections import connections I get the error "ImportError: No module named elasticsearch_dsl.connections". When I use this same command in the Django shell, it works fine. search.py from elasticsearch_dsl.connections import connections from elasticsearch_dsl import DocType, Text, Date, Boolean, Integer, Keyword, fields from elasticsearch.helpers import bulk from elasticsearch import Elasticsearch from .models import HomeGym, Country, Rating connections.create_connection() class HomeGymIndex(DocType): title = Text() price = fields.FloatField() tags = Keyword() city = Text() country = Text() rate = Integer() opusApproved = Boolean() def bulk_indexing(): HomeGymIndex.init() es = Elasticsearch() bulk(client=es, actions=(b.indexing() for b in HomeGym.objects.all().iterator())) This leads to an ImportError on line 1. "No module named elasticsearch_dsl.connections" The same import statement works in the shell though. I've already done a pip install of elasticsearch and elasticsearch-dsl inside my virtualenv. Here is the file structure my_website/ elasticsearch/ #elasticsearch files pulled from github elasticsearch-5.5.2-SNAPSHOT/ #elasticsearch files bin/ elasticsearch opus/ manage.py homegymlistings/ models.py search.py #other standard app files opus/ #standard files for main django branch my_virtualenv/ bin/ activate Why does my import statement only fail when called inside the search.py file located inside the homegymlistings app? -
Mapping Multiple model classes in Django Tastypie API
I need to create a bulk API that returns the customer details for all the applications (UAIDs) and need to add a filter for the customer type (application owner or application SME etc.) Model Classes - App_contacts, contacts Desc Contacts contact_id int(11) NO PRI auto_increment contact_type varchar(45) NO last_name varchar(100) NO first_name varchar(100) YES middle_name varchar(100) YES userid varchar(45) YES MUL email_address varchar(255) YES Desc app_contacts app_contact_id int(11) NO PRI auto_increment contact_type varchar(45) NO modified_on datetime NO contact_id int(11) NO MUL modified_by_id int(11) NO uaid varchar(45) YES MUL Expected Example Response from the API - { "result": { "UAID-00001": { "contacts": { "app_business_owner": [ { "email_address": "xez@tt.com", "first_name": "x", "full_name": "xez", "last_name": "z", "middle_name": "e", "status": "active", "userid": "xez" } ], "app_owner": [ { "email_address": "ced@tt.com", "first_name": "c", "full_name": "ced", "last_name": "d", "middle_name": "e", "status": "active", "userid": "ced" } ], "app_sme": [ { "email_address": "aeb@tt.com", "first_name": "A", "full_name": "A B", "last_name": "B", "middle_name": "E.", "status": "active", "userid": "aeb" } ] }}}} Code - class CustomContactsResourceBulk(AppMapBaseResource): class Meta(AppMapBaseResource.Meta): queryset = AppContacts.objects.all() resource_name = 'contacts/bulk' allowed_methods = {"get", "post"} def prepend_urls(self): return [url(r"^appmap/(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view("get_custom_bulk"), name="api_get_custom_bulk"), ] def get_custom_bulk(self, request, **kwargs): """ Based on the request input, we will send … -
It didn't want to install in my virtualenv
(goat) ┌─╼ [~/Projects/Personal_Projects/Goat_TDD_Project/superlists] └╼ pip3 install django-extensions Collecting django-extensions Using cached django_extensions-1.9.0-py2.py3-none-any.whl Requirement already satisfied: six>=1.2 in /home/jeremie/.local/lib/python3.5/site-packages (from django-extensions) Installing collected packages: django-extensions Exception: Traceback (most recent call last): File "/home/jeremie/.local/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/jeremie/.local/lib/python3.5/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/home/jeremie/.local/lib/python3.5/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/home/jeremie/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/home/jeremie/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/home/jeremie/.local/lib/python3.5/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/home/jeremie/.local/lib/python3.5/site-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/home/jeremie/.local/lib/python3.5/site-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib/python3.5/os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/lib/python3.5/site-packages/django_extensions' I am trying to understand why I have this issue when I try to install django-extensions. Yet I am in the virtualenv (wrapper) goat, but it didn't want to install in it. How could I fix that? -
SynapsePay & Django conflicting instances of User issue
My name is omar. I am working on a django project that is using the SynapsePay api for monetary transactions. I am getting an issue where I have two instances of the same object(User). Django uses the 'User' object when new users are created within the django application. Synapse uses the 'User' objects when a new user is created within their api. When i try to use the SYnapse api, I am starting to get conflicting uses of the same vauralbe. In the import statements, when I imported the user from the Synapse Api, I saved the instance of the user as SynapseUser and that is what I am using to interact with the application. There are parts of the api that are not controllable by me that use the 'User' object within the Api and It is grabbing the wrong object or trying to grab a key that doesnt exist in the key that is being passed. Here is the all the code I have and the error that I am trying to get... THe following code is to grab the forms content and test the bank authroization with the api.. Here is a link to the api github … -
How can I make a trailing slash optional for included module urls
I have a third party django app with it's own urls but they require a trailing slash. How can I support both with and without the slash? -
Django form field required based on field from another form
I have a form in which I would like to set the form fields 'required' based on the value from another form in the same view Example class FormA(forms.Form): field_a = forms.CharField() field_b = forms.CharField() class FormB(forms.Form): field_x = forms.ChoiceField(choices = [('a', 'a'), ('b', 'b')]) I would like to set the fields in FormA required during the validation of the form, based on the value of fields_x in FormB. Is there a clean way to do this in django ? -
Describe the polymorphic relationship of Django
Tell me how to describe this connection: There is a table in which there can be different types of records (Type1, Type2 or Type3). models.py from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType class General(models.Model): field1 = models.CharField(max_length=512, blank=True, null=True) field2 = models.CharField(max_length=512, blank=True, null=True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Meta: db_table = 'General' class Type1(models.Model): name = GenericRelation(Product) address = models.CharField(max_length=512, blank=True, null=True) number = models.CharField(max_length=256, blank=True, null=True) class Meta: db_table = 'Type1' How to make a connection and choose what I want to type in a type, for example Type2? -
Is it needed to add reCaptcha to built in Django's login form?
Hello I'm new to Django and I'm using Django's built in forms to login my users, also I have a contact form where I'm using Google reCaptcha to avoid attacks. I was wondering if it is needed to add reCaptcha to my login form. I have heard Django takes care most of security and I don't want to repeat code if default login form is already prepared for brute force attacks. In case its better to add reCaptcha to default login form how can I process the validation? In my contact form I call Google's API to verify user click within my views, but I don't feel comfortable adding that code inside the auth_views.LoginView class. Thanks! -
Use JSON to create Model objects - Django
I have an external URL containing JSON with the following fields: id, name, image_url, title and bio This is the URL: https://api.myjson.com/bins/16roa3 So my question is: How do I save this to my Django admin page if I created the following model that matches the Keys of the JSON? from django.db import models class Person(models.Model): name = models.CharField(max_length=254) image_url = models.ImageField(blank=True) title = models.CharField(max_length=254) bio = models.CharField(max_length=20000) vote = models.IntegerField() My goal is to be able to create a voting app that lets you vote for each individual person defined by the JSON. Here is the longer version of this question: Create object models from external JSON link- Django -
Django filters with pagination not keeping state
In my django project I am using django filters and pagination. When I click the next link to go to the next page, I lose my state. i have tried some ideas from here but nothing has done the trick yet. Any ideas on why this happens? html <div class="col-xs-4 clearfix text-center"> {% if relations.has_next %} <div class="pull-right"> <a href="?page={{ relations.next_page_number }}{% if createdBy %}&createdBy={{ createdBy }}{% endif %}{% if project %}&project={{ project }}{% endif %}{% if createdBefore %}&createdBefore={{ createdBefore }}{% endif %}}">Next &raquo;</a> </div> {% endif %} </div> View def relations(request): from annotations.filters import RelationSetFilter qs = RelationSet.objects.all() filtered = RelationSetFilter(request.GET, queryset=qs) qs = filtered.qs for r in qs: print r.__dict__ paginator = Paginator(qs, 20) page = request.GET.get('page') createdBy = request.GET.get('createdBy') createdAfter = request.GET.get('createdAfter') createdBefore = request.GET.get('createdBefore') project = request.GET.get('project') terminal_nodes = request.GET.get('terminal_nodes') occursIn = request.GET.get('occursIn') try: relations = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. relations = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. relations = paginator.page(paginator.num_pages) context = { 'paginator': paginator, 'relations': relations, 'params': request.GET.urlencode(), 'filter': filtered, return render(request, 'annotations/relations.html', context, {'filter': filtered})' Urls Url when filters are applied: /relations/?createdBy=&occursIn=&createdAfter=&createdBefore=&terminal_nodes=&project=1 Url … -
Using Jinja2 contextfunction like django inclusion tag
I am trying to add a contextfunction rendering a menu html, to Jinja2 environment globals. I have written: @contextfunction def main_menu(context, parent, calling_page=None): menuitems = parent.get_children().live().in_menu() for menuitem in menuitems: menuitem.show_dropdown = has_menu_children(menuitem) # We don't directly check if calling_page is None since the template # engine can pass an empty string to calling_page # if the variable passed as calling_page does not exist. menuitem.active = (calling_page.path.startswith(menuitem.path) if calling_page else False) return render ( context['request'], 'personal_web/tags/main_menu.html', { 'calling_page': calling_page, 'menuitems': menuitems, }) But when I use {{ main_menu( parent=site_root, calling_page=self) }} in my template and call the function it renders '' What am I doing wrong? -
Passing URL params from the database
I am trying to build a full stack web application. In my database, I have a table with lots of data that looks something like: SHOWS ID show_name show_number 1 First Show 2 2 Second Show 1 3 Third Show 1 4 fourth Show 2 5 Fifth Show 3 6 Sixth Show 1 If you can see, I have show number as a column on the side. This show number could be any number from 1-32. What I am trying to do is to have a URL that will have those show_number as a type of parameter by setting up url pattern. In my urls.py urlpatterns = [ url(r'^show/(?P<show_number>\d+)$', views.generate_screen), ] And when I go to …/show/1/, All rows with show_number 1 will be on that page. If I go to …../show/2/ all rows with show_number 2 will go there and so on. In my models.py: def show_screen(self): with connection.cursor() as cursor: cursor.execute("SELECT show_number, show_name FROM shows ORDER BY show_number ASC;") data = cursor.fetchall() return data In my views: def slideshow(request): context = { "shows": Show.objects.all() } return render(request, 'index.html', context) Towards the end of this project, my goal is to let my url dynamically change every some seconds. Is … -
Execute code in django as a timed event
I have a message board application that needs to collect and display messages without any user input or action. I am currently doing this by refreshing the page using the html meta refresh tag. I realize that this is not a great solution. This is the relevant section that I want to run frequently without refreshing the page. {% if grams_list %} #if there exists any messages for the user {% for g in grams_list %} #for each message <h2 class="gram-display">{{ g.message }}</h2> #display the message {% endfor %} {% else %} #otherwise display this nice picture <h2 id="nograms" class="gram-display">No grams right now.</h2> <img id="bird" src="/static/cardinal_from_pixabay.jpg"> {% endif %} Is this the sort of thing that could be accomplished with JavaScript? I know that it is possible to have javascript trigger a Javascript function every so often, but is this possible to trigger this event? Alternately, does Django have some built-in function that does this? Could it be handled by signals (I looked at signals but didn't really understand them, though they looked like they had potential to be useful). -
Converting existing python classes into Django Models
I have a small program with a command line interface that uses a number of python classes with thorough implementations. I want to scrap the command line interface and wrap the app within a Django app, but I'm just learning Django and I'm unfamiliar with the conventions. I have a number of classes, in-memory storage structures, getters/setters etc and I'd like to convert them into Django models so that I can persist them to the database and interact with them around the app. Is there a general approach for doing something like this? Should I just inherit the django.db.models.Model class in my existing classes and set them up for direct interaction? Or is there a better, more general/conventional way to do this? Thanks for any help ahead of time... -
Django template doesn't output values to HTML table cells
I have the following template: <table> <tr> <th>Monday</th> <th>Tuesday</th> <th>Wednesday</th> <th>Thursday</th> <th>Friday</th> <th>Saturday</th> <th>Sunday</th> </tr> {% for row in table %} <tr> {% for i in week_length %} <td>{{row.i}}</td> {% endfor %} </tr> {% endfor %} </table> And the following view: def calendar(request): template_name = 'workoutcal/calendar.html' today_date = timezone.now() today_year = today_date.year today_month = today_date.month today_day = today_date.day table = maketable(today_date) # Creates something like: [[None, 1, 2, 3, 4, 5, 6],[7, 8, ...],...,[28, 29, 30, 31, None, None, None]] template = loader.get_template('workoutcal/calendar.html') #Workout.objects.filter("Workouts lie between certain dates") context = { 'workout_list': Workout.objects.filter(date__year = today_year, date__month = today_month, date__day = today_day), 'table': table, # The calendar 'week_length': range(7), } return HttpResponse(template.render(context, request)) When I access the page (localhost:8000/workoutcal), nothing except for the table headers is output. It looks like this: I can't figure out why Django is not putting my output into the cell. I want no output for elements of the list that are None, and then simply the element content (all are strings) in for all other elements. Any ideas? -
Setting up celery with django
New to celery and django, and have a working demo project I'm using as a starting point. Here's how it creates a celery app # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ch.settings') app = Celery('ch') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() the only function binded to using @app.task(bind=True) in this py file are process_image and debug_task this command works in the project celery worker --app ch.celery_app the test project name is ch my project name is revamp and here's how I implemented it # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'revamp.settings') app = Celery('revamp') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() I binded to full_render but when I try samuel@samuel-pc:~/Documents/code/revamp$ celery … -
Does looking at a Django model's fk_id attribute trigger a database lookup?
I'm writing a script that needs to go through several hundreds of thousands of models and (depending on the presence or absence of a blank=True, null=True ForeignKey field) perform certain actions. Given the following code: class RelatedItem(models.Model): name = models.TextField() class Item(models.Model): related_item = models.ForeignKey(RelatedItem) items = Item.objects.all() for item in items: if item.related_item: # Do stuff I know that the item.related_item will trigger a database lookup. Hoping to avoid this, I was wondering if I could instead do this: items = Item.objects.all() for item in items: if item.related_item_id: # Do stuff Would that item.related_item_id still trigger the database call, or is that field stored in the model, and potentially therefore run faster? EDIT: Note, I'm not even looking to use the related_item, so I don't think I need to employ a select_related or prefetch anything. That said, if the database lookups are inevitable, and that would also speed up my query (and not bog down my machine's memory as 100k items are prefetched) I could also go for that. EDIT 2: I also can't change the initial queryset from Item.objects.all() to Item.objects.filter(related_item__isnull=False). My example below is a simplification, but the full function needs to iterate through all objects in … -
How can I make a trailing slash optional on a Django Rest Framework SimpleRouter
The docs say you can set trailing_slash=False but how can you allow both endpoints to work, with or without a trailing slash?