Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checkbox in Django, not linked Bootstrap checkbox to Models/database not working in both ways
I know this is a question that has been around in different formats, but for some reason, I can't find a solution for myself. The problem: when I'm adding a checkbox in django admin, I can see it on page, but not in forms, when I'm trying to edit item outside of the admin (using Boostrap forms). here is my html file for edit: <div class="checkbox"> <label class="form-check-label" for="inputprocurement" style=color:#D3D3D3>On Order:</label> <input type="checkbox" class="form-check-input" id="inputprocurement" aria-describedby="editprocurement" value="{{ get_item.on_orderp }}" name = "on_orderp"> </div> here is a relevant part from models.py file: on_orderp = models.BooleanField("inputprocurementcheck", default = False) and the view.py: def edit_procurement(request, listp_id): if request.method =='POST': current_itemp = Procurement.objects.get(pk=listp_id) # add `request.FILES or None` for file upload form = ProcurementForm(request.POST or None, request.FILES or None, instance=current_itemp) if form.is_valid(): form.save() messages.success(request, ('Item Has Been Edited!')) return redirect('procurement') else: messages.success(request, ('Seems Like There Was An Error...')) return render(request, 'edit_procurement.html', {}) so, when I have a checkbox on my item: I can't see the checked box, when I'm on my forms in edit: and if the checkbox is on, and I'm testing the edit function with a checkbox on, nothing is changed. if the checkbox is on, and I'm testing the edit function … -
longclaw demo bug from rest_framework.decorators import detail_route, list_route ImportError: cannot import name 'detail_route'
When i start Longclaw I get What should I change? I tried with docker and with manage.py runserver. from rest_framework.decorators import detail_route, list_route ImportError: cannot import name 'detail_route' Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File … -
Django legacy database inspectdb removes "_id" suffix from field names
I am having a problem using inspectdb in django for a legacy database. I believe my issue is essentially the opposite of what is described here: Django suffix ForeignKey field with _id Many field names in my database end with "_id". Upon running inspectdb, those fields which end in "_id" and are also ForeignKeys or OneToOneFields have the "_id" removed: class AssayClassMap(models.Model): ass_cls_map_id = models.BigIntegerField(primary_key=True) assay = models.ForeignKey('Assays', models.DO_NOTHING, blank=True, null=True) I can fix this by changing the above lines to this: class AssayClassMap(models.Model): ass_cls_map_id = models.BigIntegerField(primary_key=True) assay_id = models.ForeignKey('Assays', models.DO_NOTHING, blank=True, null=True, db_column='assay_id') The issue is that there are hundreds of these that will need to be manually changed each time the model file is generated both for this database and other databases. I can come up with a script to correct these problems but I'd like to think there is some workaround. Thanks -
Django-Blog comments form not appearing
I am currently following the Django-Blog tutorial on the Django-Central site and I am trying to add the comment section to the blog. I have got my comments displaying, but I cant seem to get the form to display so that site visitors can add comments to the blog posts. views.py from django.shortcuts import render, get_object_or_404 from django.views import generic from .models import Post from .forms import CommentForm # Create your views here. class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) # Fetching the comments that have active=True comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.PSOT) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the databse new_comment.save() else: comment_form = CommentForm() print('Comments:', comments) return render(request, template_name, {'post': post, 'comments': new_comment, 'new_comment': new_comment, 'comment_form': comment_form}) forms.py from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body') post_detail.html <div class="col-md-8 card mb-4 mt-3"> … -
Multiple database creation and migration not working
DATABASE_ROUTERS = ['contact.models.DemoRouter'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'bsdsample5', 'USER': 'postgres', 'PASSWORD': 'absd', 'HOST': 'localhost', 'PORT': '', }, 'bsdsample4': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'bsdsample4', 'USER': 'postgres', 'PASSWORD': 'bsd', 'HOST': 'localhost', 'PORT': '', } } than contact models class SpamExternalInquiry(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) email = models.CharField(max_length=256) date_sent = models.DateTimeField(default=timezone.now) subject = models.CharField(max_length = 200) message = models.TextField(max_length = 2000) spam_score = models.IntegerField() class Meta: app_label = 'bsdsample4' def __str__(self): return self.email + ' - ' + self.subject + ' - ' + str(self.date_sent) def initialize(self, extInquiry): self.first_name = extInquiry.first_name self.last_name = extInquiry.last_name self.email = extInquiry.email self.date_sent = extInquiry.date_sent self.subject = extInquiry.subject self.message = extInquiry.message class DemoRouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'bsdsample4': return 'bsdsample4' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'bsdsample4': return 'bsdsample4' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'bsdsample4' or \ obj2._meta.app_label == 'bsdsample4': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'bsdsample4': return db == 'bsdsample4' return None SO I am trying to do migrate and make migrations, unfortunately its taking random tables of my database and migrating it to bsdsample5.APart from the one I actually want, spamexternalinquiry. I … -
Creating Microsoft Active Directory Accounts from Django Web Application
If I wanted to create new user accounts and set attributes in an on-premise deployment of Microsoft Windows Server 2019 Active Directory from a Django web application, how would I go about accomplishing this? Is there a REST API I can use, or is there some other solution? Could I use ADFS to provision AD users? -
Django request.GET.get() gives None every two times
I'm trying to use some ajax request to echange between django views and the templates but i'm experiencing a strange behavior with the request.GET. Django sends an error saying that the data in parameter of the json.loads() shouldn't be empty; but if I try to debug this code, it seems that the request.get('selects',None) returns 'None' every two times. When requesting request.GET.get('selects') in the console, I get: None the first time and '[{"pk":"57226796-0960-428a-88aa-ba4120ad34b4"}]' the second time, then None again then '[{"pk":"57226796-0960-428a-88aa-ba4120ad34b4"}]' at the third attempt. every odd attempt return None.... what do I wrong ? views.py class AjaxRenameView(View): def get(self,request): import pdb; pdb.set_trace() selects=request.GET.get('selects', None) selects=json.loads(selects) pkq= [ pk['pk'] for pk in selects] if len(pk)==1: folder=Folder.objects.filter(pk=pks[0]) spotler=Spotler.objects.filter(pk=pks[0]) if folder: form=FolderRenameForm(instance=folder) title=_('rename folder') elif spotler : form=SpotlerRenameForm(instance=folder) title=_('rename project') context={'form':form,'title':title,'submit':_('rename'),'has_error':False} html_form = render_to_string('includes/modal_form.html', context, request=request, ) return JsonResponse({'html_form': html_form}) return JsonResponse({'has_error':True, 'message':_('an error has occured while renaming')}, safe=False) def post(self,request): pass folder.js //... function ajaxAction(selects,url,next){ // when clicked on item of menu (rename, share, move...) $.ajax({ type:"GET", data:{'selects':JSON.stringify(selects),'next':next}, url: url, dataType:"json", beforeSend: function () { $("#Modal .modal-content").empty(); }, success: function (data) { $("#Modal .modal-content").html(data.html_form); } });//ajax }//function ajaxAction //... console (Pdb) request.GET.dict() {'selects': '[{"pk":"57226796-0960-428a-88aa-ba4120ad34b4"}]', 'next': '/fr/wf/myfiles/'} (Pdb) request.GET.get('selects') (Pdb) request.GET.get('selects') '[{"pk":"57226796-0960-428a-88aa-ba4120ad34b4"}]' (Pdb) … -
OAuth/OIDC Implementation with Django
Is there a way to integrate Django's built-in authentication/authorization with an external OAuth/OIDC provider? Basically I want to be able to use Django permissions to lock up some data allowing only users with the is_staff = True to be able to mutate data. However, I'm not trying to some typical login and registration with email and password. I want to use this external authentication ... which in the end, returns an id token. I realize I could simply design my flow such that I will JWT decode the id token and get_or_create a User instance as needed, probably without a password. But to be honest, I'm not sure if decoding with PyJWT is advisable from a security perspective. Most OpenID Connect implementations do extensive signature checking via the well defined configuration. I just feel like I'm reinventing the wheel here, and not even a stable wheel at that. Any ideas? -
Huey Task Queue handle error on last retry only & retrieve exception traceback
Currently have this snippet set up in my tasks.py so that an email is sent to the Django project's admins by huey whenever a task fails: from django.core.mail import mail_admins from huey import signals from huey.contrib import djhuey as huey @huey.signal(signals.SIGNAL_ERROR) def task_error(signal, task, exc): subject = f'Task [{task.name}] failed message = f"""Task ID: {task.id}' Args: {task.args} Kwargs: {task.kwargs} Exception: {exc}""" mail_admins(subject, message) This results in the following (example) email subject [Django] Task [test_task] failed and body: Task ID: 89e4bfb3-3cd3-4d6f-8693-68874caf21ec Args: (123,) Kwargs: {} Exception: division by zero which is pretty slick but... questions: Right now, this is triggered whenever a task fails, including retries. I would like it to be sent only in the case all retries failed. So if a task has retries=2, right now I receive 3 emails (original error + 2 retries). How to have it send the email only on the last retry? Is there a way to print the exception's exc traceback? P.S. I tried setting it up via Django project logging, but approach this offers finer-grained control, so I'm satisfied with it. -
how to match two lists in elasticsearch django using query?
I have two lists, one the skills and other core skills. I want a query in such a way that if any element in skills match atleast one element in core skills, I get a hit. Here is my query: skills = ['kitchen', 'delivery'] core_skills = ['kitchen', 'house_keeping', 'bar'] query = { "query" : { "bool" : { "must" : [ { "terms" : { "skills" : "core_skills" } } ] } } } -
Django REST Framework: filtering a HyperlinkedRelatedField()
I'm just wondering, I have the following unfinished serializer where I am utilising a HyperlinkedRelatedField as follows: from rest_framework import serializers from api.v2.SurfBookings.models import SurfBooking class SurfBookingSerializer(serializers.ModelSerializer): tickets = serializers.HyperlinkedRelatedField( many=True, read_only=False, queryset=tickets.objects.filter(booking=self) ) # tickets_hyperlink_identity = HyperlinkedIdentityField(view_name='ticket-list') class Meta: model = SurfBooking fields = '__all__' I was wondering, for the line queryset=tickets.objects.filter(booking=self) I have just guessed at self, but essentially how do I filter the tickets object where the booking ForeignKey relationship is for the Booking instance? Would it be self.obj? -
Change the default alert messages from Django Allauth?
I'm using the standard login templates from django-allauth and I wish to style the alert box differently than the default one provided. (And also remove the <ul> tags through a custom class) e.g class DivErrorList(ErrorList): def __str__(self): return self.as_divs() def as_divs(self): if not self: return '' return '%s' % ''.join([e for e in self]) 1) How would I style the alert? 2) How do I add a custom class to the loginform? -
ImportError: cannot import config from django
I am using, pycharm professional for django project. I have installed decouple but it shows error while importing config. How can I solve this problem ? it shows this error: ImportError: cannot import name 'config' from 'decouple' (/home/bijaythapa/Desktop/myfirstdjangoproject/venv/lib/python3.7/site-packages/decouple/__init__.py) but, while running server, if if hit print(config("SECRET_KEY")), it prints the value. -
Integrity Error in running django tests with multiple instances of TestCase class
The tests defined for the first TestCase execute successfully. However, for the next TestCase I get an integrity error indicating that the fixtures from the previous TestCase were not cleaned up after the test run. This happens only with Postgres. The same tests run successfully with SQLite. If I put these tests within the same class, they run successfully even with postgres. Any help in figuring out whats going on here will be appreciated. test_run.py : User = get_user_model() client = Client() class DemoTest(TestCase): fixtures = ['app1fixture', 'auth', 'app2fixture', 'app3fixture'] def test_demo(self): u = User.objects.create(username='Apple') self.assertEqual(u.username, 'Apple') class DemoTest2(TestCase): fixtures = ['app1fixture', 'auth', 'app2fixture', 'app3fixture'] def test_demo2(self): u = User.objects.create(username='Banana') self.assertEqual(u.username, 'Banana') Error : django.db.utils.IntegrityError: Problem installing fixture '/home/shaily/myapp/app1/fixtures/app1fixture.json': Could not load app1.Profile(pk=1): duplicate key value violates unique constraint "app1_profile_user_id_key" DETAIL: Key (user_id)=(1) already exists. -
Django ORM filter multiple fields using 'IN' statement
So I have the following model in Django: class MemberLoyalty(models.Model): date_time = models.DateField(primary_key=True) member = models.ForeignKey(Member, models.DO_NOTHING) loyalty_value = models.IntegerField() My goal is to have all the tuples grouped by the member with the most recent date. There are many ways to do it, one of them is using a subquery that groups by the member with max date_time and filtering member_loyalty with its results. The working sql for this solution is as follows: SELECT * FROM member_loyalty WHERE (date_time , member_id) IN (SELECT max(date_time), member_id FROM member_loyalty GROUP BY member_id); Another way to do this would be by joining with the subquery. How could i translate this on a django query? I could not find a way to filter with two fields using IN, nor a way to join with a subquery using a specific ON statement. I've tried: cls.objects.values('member_id', 'loyalty_value').annotate(latest_date=Max('date_time')) But it starts grouping by the loyalty_value. Also tried building the subquery, but cant find how to join it or use it on a filter: subquery = cls.objects.values('member_id').annotate(max_date=Max('date_time')) -
python-django Crear archivo zip bytesio- con archivos descargados con BytesIO
I download some files with ftplib and save them with ByteIO, so they are stored in the buffer, now what I want to do is create a zip file with ByteIO with the downloaded files. Basically I have the following: files_names = ["file.pdf","file2.pdf"] r = BytesIO() stream = BytesIO() zipobj = ZipFile(stream,'w') for file in files_names: ftp.retrbinary("RETR" + file, r.write) zipoj.write(r.getvalue() zipobj.close() return stream The error that appears to me is: "Embebbed null character in path" Does anyone have any idea how I could solve it? -
Django existing database seperation
SO I Have a models.py under one of my modules, I want this module to be different database. I am giving sample code below, The problem is that I dont want to lose existant data in database 1.I just want to make new database 2, and migrate this models.py related to this module to database 2. How can I make django app with 2 databases? and most importantly how to migrate the existing data in database 1 to database2 , and remove info from database 1. from django.db import models class UserManual(models.Model): name = models.CharField(max_length=15, default="BSD") manual = models.FileField(upload_to="manual/") class Policy(models.Model): name = models.CharField(max_length=15, default="BSD_1") policy = models.FileField(upload_to="policy/") Django 2.2.* and Python 3.6.9 -
Django REST Framework - Create Serialization for foreign key relation
I've always wondered what the Django way is to do this, but let's say I have an object "Book" as follow: class Book: name = models.CharField() And also a Chapter model that links to a book instance. class Chapter: order = models.IntegerField() content = models.TextField() book = models.ForeignKey('books.Book', on_delete=models.CASCADE) I'm wondering, how best is it to create a viewset for a retrive and list GET for either a book or books that also returns it's related Chapters? -
I'm deploy my django project with uwsgi and nginx and i get apache defult page
I'm make all things to run my project and it run and uwsgi run and nginx server run all good but when i open my host name in browser i get this page what should i do to open my project page enter image description here and i didn't know why this page rise Though i didn't use Apache in my project at all and thanks for your time . enter image description here -
How to download an empty folder using Django?
I am trying to set a link which will download an empty folder upon clicking. Is there any way (javascript/ jQuery) to do it in Django? In several tutorials, they zipped the folder and then downloaded it from the server. I need to create a folder in the server with a unique id for my application. If someone downloads it, they will get an empty folder without zipping it. -
Configure Selenium use pytest test database in django app so that CI is supported
I am running a dockerized django app and I am running selenium tests using pytest. It seems like pytest is using a different database for running tests than my development app. That means I can't use fixtures (because fixtures are created in a different db). I am confused on three levels: Firstly, I see many tutorials using fixtures with selenium and pytest. So that means selenium is using the testdatabase. Secondly according to this answer pytest has to use the same testdatabase as my develompent app (Django tests with selenium not loading fixtures) Thirdly according to django docs https://docs.djangoproject.com/en/3.0/topics/testing/overview/ a test db is created before every testrun and then destroyed. That bears the following trouble for me: I am running my selenium tests also within a CI pipeline. So I need to be able to create fixtures or instances in the db during execution. I have read that selenium shouldn't be used for model tests. Ok, but almost all my views are protected so I need to login, so I need a user, so I need a model. Thus, my question: How can I run pytest with selenium using the same database so that fixtures are supported, which is also … -
Django - redirect to view after clicking on favorite link
In my app I want to create favorite system: user input url some data is calculated then user can add this link to favorite After clicking add user is redirected to other endpoint which returns all his favorites links. At this point I want to add possibility which allow user to click on one of his favourites, return to other view and calculate some data. My views.py def home(request): """this function return form which allow user to input link""" if request.method =='POST' url = request.POST['url'] request.session['url'] = url return redirect('bokeh') return render(request,'base.html') After this, bokeh.html is returned and have some data like charts def bokeh(request): url = request.session.get('url') cl = CalculationLogic() return cl.get_data_from_url(request,url) In this view, there is a button which allow add to favorite. After clicking, method is called: def favorites(request): url = request.session.get('url') repo = Repository(url=url,user=request.user) repo.save() repo.repositorys.add(request.user) #adding value to ManyToMany field user = User.objects.get(username=request.user.username) repos = user.users.all() #return all url which current user has in favorites return render(request,'favorites.html',{'repos':repos}) And in my favorites.html {% extends 'bokeh.html' %} {% block content %} <h1>Favorites repositorys for {{ user }}</h1> {% for r in repos %} <br><a href="{% url 'bokeh' %}">{{ r }}</a> {% endfor %} {% endblock %} So, … -
websocket run async function but returns error: asyncio.run() cannot be called from a running event loop
I'm trying to use django-channels 2 to create websockets. I need to run a async method which should return the output of a command, so I can pass the data back to the user on my website. My problem is that it will not let me run it and comes out with the error: asyncio.run() cannot be called from a running event loop What am I doing wrong and what can I do about it? consumers.py class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept" }) user = self.scope['user'] get_task_id = self.scope['url_route']['kwargs']['task_id'] await asyncio.run(self.run("golemcli tasks show {}".format(get_task_id))) await self.send({ "type": "websocket.send", "text": "hey" }) async def websocket_receive(self, event): print("receive", event) async def websocket_disconnect(self, event): print("disconnected", event) async def run(self, cmd): proc = await asyncio.create_subprocess_shell( cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await proc.communicate() print(f'[{cmd!r} exited with {proc.returncode}]') if stdout: print(f'[stdout]\n{stdout.decode()}') if stderr: print(f'[stderr]\n{stderr.decode()}') Traceback: Exception inside application: asyncio.run() cannot be called from a running event loop File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/consumer.py", line 62, in __call__ await await_many_dispatch([receive], self.dispatch) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/utils.py", line 52, in await_many_dispatch await dispatch(result) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) … -
Django: Update multiple rows with value from relation
We have thousands of rows in our DB that all needs a database migration applied. We have so many rows that spans goes back 8 years, and it's not really feasible for us to run save() on each individual instance, as in this example here: update_list = OrderProduct.objects.filter( product__isnull=False, title="unnamed") for op in update_list: op.title = op.product.title op.save() # We would prefer a update() query rather than individual saves So we are trying to do this with a db query. I'm aware that F() doesn't support joins when using it inside update(), which is why I was trying to be smart with the following: OrderProduct.objects\ .filter(title="unnamed", product__isnull=False)\ .annotate(copy_title=F('product__title'))\ .update(title=F('copy_title')) Unfortunately that doesn't work, so I'm wondering if there is a simple way to achieve this with a django update(), rather than cycling through every row. -
Is it more efficient to use serializers for constant changing fields or model fields
I am currently trying to redesign a Django database and have come across an issue where we have multiple fields that update based off other fields. Is it better to keep them saved as a model field or use a serializer that calculates it when we need it? Are there pros/cons to using one versus the other?