Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Annotate on reverse many-to-many
I'm trying to work out why this doesn't work:- class A(models.Model): contacts = models.ManyToManyField(Contact) class Contact(models.Model): name = models.CharField() If I try and get a count of how many A there are with multiple contacts:- A.objects.annotate(num_contacts=Count('contacts')).filter(num_contacts__gt=1).count() there are 10. but if I have a particular contact and I want to get a count of how many A's they are connected to that have more than 1 contact on them:- B.a_set.annotate(num_contacts=Count('contacts')).filter(num_contacts__gt=1).count() I get 0. The num_contacts count always comes out as 1, even when the A has more than 1 contact. I must have missed something silly but I can't see it. Any ideas? -
django select_for_update(nowait=False) in transaction.atomic() does not work as expected
I have a django app that needs to get a unique ID. Many threads run at the same time that need one. I would like the IDs to be sequential. When I need a unique ID I do this: with transaction.atomic(): max_batch_id = JobStatus.objects.select_for_update(nowait=False).aggregate(Max('batch_id')) json_dict['batch_id'] = max_batch_id['batch_id__max'] + 1 status_row = JobStatus(**json_dict) status_row.save() But multiple jobs are getting the same ID. Why does the code not work as I expect? What is a better way to accomplish what I need? I cannot use the row id as there are many rows that have the same batch_id. -
"No such table" error coming from serializers.py file, when running migration command
I recently moved my Django app from using the default User model to a custom User model, and since this is not recommended to do mid-way through a project, I had to drop the database and migrations and recreate migrations and run migrate. This works fine when I comment out the entire serializers.py file, as well as comment out everywhere it is referred to. However, now that I want to be able to action all the new migration steps at production level WITHOUT having to comment out serializers.py. I know that I have referenced a table that doesn't technically exist so, I'm just wondering what is the best way to do this? Here is my serializers.py code: class MyModelSerializer(serializers.Serializer): features = Feature.objects.values_list("feature_name", flat=True) # Feature is a model feature = serializers.ChoiceField(features) # this is where the error happens The error says: "no such table: myapp_feature" -
Best way to store multiple date in one object django
I have model Topic. Now i have date = models.DateTimeField class Topic(models.Model): owner = models.ForeignKey(Profile, on_delete=models.SET(GUEST_ID)) seminar = models.ForeignKey(Seminar, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(default='') speaker_name = models.CharField(max_length=200, default='') date = models.DateTimeField(null=True, blank=True) but i want to save multiple date for example: 27.11.2022,29.11.2022,01.01.2023. I have idea to write date = models.CharField() and save dates as string Is there a better solution? -
Django DateTimeField Timestamp value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format
The environment is: Django 4.0 (venv) Python 3.8 Postgres 15 Elementary OS 6.1 The initial model: class MyModel(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Upon saving a new record (without providing any value for "created" nor "updated") the result was: django.core.exceptions.ValidationError: ['“1669827388000” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] Then I've followed some suggestions to do this: class MyModel(models.Model): created = models.DateTimeField(editable=False) updated = models.DateTimeField(editable=False) # Still doesnt work: It gets a timestamp def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() self.updated = timezone.now() return super(Token, self).save(*args, **kwargs) The result was exactly the same (of course the timestamp's value changed). I've tried variations with django.settings settings.USE_TZ from True to False & vice versa. Traceback: Traceback (most recent call last): File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/PROJECT_NAME/.venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) … -
How to assign multiple api views to single endpoint in django rest framework?
I have a model named Article and a few api views for it. They are divided for diffrent purposes (for example ArticleUpdateAPI class for UPDATE http method, ArticleDeleteAPI for DELETE method etc). In urls.py they are separated to diffrent endpoints (aritcle/pk/update, /article/pk/delete etc). As I know, it's not good practice to build endpoint like this, so I want to bind them to single url and use diffrent classes for handling diffrent http methods. Is it possible and how? Examples are below ArticleAPI.py class ArticlePostAPI(generics.CreateAPIView): serializer_class = ArticleSerializer permission_classes = [ permissions.IsAuthenticatedOrReadOnly ] def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({ "comment": CommentSerializer.data }, status=201) class ArticleRetrieveAPI(generics.RetrieveAPIView): serializer_class = ArticleSerializer queryset = Article.objects.all() permission_classes = [ permissions.AllowAny ] class ArticleListAPI(generics.ListAPIView): serializer_class = ArticleSerializer queryset = Article.objects.order_by('number', 'headline') permission_classes = [ permissions.AllowAny ] class ArticleUpdateAPI(generics.UpdateAPIView): serializer_class = ArticleSerializer queryset = Article.objects.all() permission_classes = [ permissions.IsAuthenticated ] lookup_field = 'pk' def update(self, request, *args, **kwargs): instance = self.get_object() if request.user != instance.author: return Response({ "errors": "Logged in user and author must be same" }, status=403) serializer = self.get_serializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) urls.py urlpatterns = [ ... # Article API path('article/post/', ArticlePostAPI.as_view(), name='article_creation'), path('article/<int:pk>/', ArticleRetrieveAPI.as_view(), name='article_retrieve'), path('article/', … -
Django Rest Framwork : Nested objects in one serializers
I have double nested serializer situation... i have three models : Reports, ReportPages and widgets , upon trying to create a specific endpoind that is : payload { "since_date": "some date", "until_date": "some other date that is greater than since_date", "report_pages": [ { "page_number": "some number" (generated from front end, of type integer) "widgets": [ { "data": ["some array"], "width": "some number", "height": "some number", "top_position": "some number", "left_position": "some number", "widget_type": "" (either "Label", "LineChart", "Bar" or "PieChart"), } ] } ] } I faced a problem with nested serializer, i was only able to create the first half which is : payload { "since_date": "some date", "until_date": "some other date that is greater than since_date", "report_pages": [ { "page_number": "some number" (generated from front end, of type integer) ] } Knowing that the creation of a report is separate from this endpoint, so i override the update method and structure looks like this : Report{ report_page{ widgets {} } } My models : class Reports(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=500, null=True) since_date = models.DateTimeField(null=True) until_date = models.DateTimeField(null=True) def __str__(self): return self.name class ReportPages(models.Model): id = models.AutoField(primary_key=True) number = models.IntegerField(null=True) report = models.ForeignKey(Reports, related_name="report_pages",on_delete=models.CASCADE) def __str__(self): return self.number … -
Make an hourly booking system using Django
I wish to create an hourly booking system in Django. I need some help regarding it : 1) I need to send text to mobile number (Free service because I can't invest money right now) ==> I have used Twilio but it can't send message to unverified numbers on basic plan 2) for booking I need to take time input of hour : ==> how can I take time input on hourly basis, It can be done as spread sheet way(how https://in.bookmyshow.com accepts seat booking) but I am unable to figure it out For frontend I'm using Bootstrap5 for sending text to mobile number I tried Twilio but it can't send text to unverified numbers on basic plan. -
Django CountryField, query by country
I have a class similar to this: class Person(models.Model): name = CharField(max_length=255) citizenship = CountryField(multiple=True) In this example a Person can have more than one citizenship. Person.objects.create(name="Fred Flinstone", citizenship="US, CA") I want to query for everyone who has a US citizenship, which would return Fred from above. Is there a django-countries way to do this? I suppose I could treat it like a CharField. If I wanted to do something more complex like "is Person a citizen of US or GB", I was hoping there was a nicer way than a complex CharField query. -
Django user is_authenticated vs. is_active
After reading the documentation, I still don't fully grasp the difference between these two User methods: is_authenticated and is_active. Both are returning a boolean. While is_authenticated is read-only (and you get an error if you try to set it), is_active can be modified and for instance you can set it to False instead of deleting account. Running these commands, will de-activate a user: >>> from django.contrib.auth.models import User >>> u = User.objects.get(pk=10) # get an arbitrary user >>> u.is_active True >>> u.is_active = False # change the value >>> u.save() # save to make effective >>> u.is_authenticated True Now, this user is still authenticated but is not able to login anymore. The login view uses authenticate(). What is actually happening that the login for a de-activated user fails? if request.method == 'POST': username = request.POST['username'] password = request.POST['password1'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) To verify the credentials you use authenticate() which returns a User object in case of success or None otherwise. I guess it returns None in case the supplied credentials are correct but is_active is False. In addition, the Jinja block {% if user.is_authenticated %} evaluates as false if is_active is … -
Customise json output, returning first item from list on Django Rest Framework
I have an API that returns the following json: { "id": 6, "lot_no": "787878", "product_id": "116110", "assay_type": "reascan_crp", "valid_from": "2022-11-21", "expiry_date": "2022-11-27", "is_active": true, "last_modified": "2022-11-21T14:29:32.435307Z", "teststrips": [ { "number": 1, "name": "", "control_line_threshold": 1.0, "testlines": [ null, null ] } ], "parameters": [ { "a": -3.0, "b": -4.0, "c": -6.0, "d": -9.0 } ] }, however I want the following output without the list on parameters: { "id": 6, "lot_no": "787878", "product_id": "116110", "assay_type": "reascan_crp", "valid_from": "2022-11-21", "expiry_date": "2022-11-27", "is_active": true, "last_modified": "2022-11-21T14:29:32.435307Z", "teststrips": [ { "number": 1, "name": "", "control_line_threshold": 1.0, "testlines": [ null, null ] } ], "parameters": { "a": -3.0, "b": -4.0, "c": -6.0, "d": -9.0 } }, serializers.py : class ParametersSerializer(serializers.ModelSerializer): class Meta: model = TeststripConfiguration fields = ('a', 'b', 'c', 'd') class TeststripSerializer(serializers.ModelSerializer): testlines = serializers.SerializerMethodField() class Meta(): model = TeststripConfiguration fields = ('number', 'name', 'control_line_threshold', 'testlines') def get_testlines(self, teststrip): upper_negative_testline = None lower_positive_testline = None if str(teststrip.batch.assay_type) != "reascan_crp": upper_negative_testline = teststrip.testlines.values('upper_negative_threshold')[0]['upper_negative_threshold'] lower_positive_testline = teststrip.testlines.values('lower_positive_threshold')[0]['lower_positive_threshold'] return upper_negative_testline, lower_positive_testline class BatchSerializer(serializers.ModelSerializer): parameters = ParametersSerializer(source='teststrips', many=True, read_only=True) teststrips = TeststripSerializer(many=True, read_only=True) assay_type = serializers.SlugRelatedField( read_only=True, slug_field='name' ) product_id = serializers.ReadOnlyField() class Meta(): model = Batch fields = ('id', 'lot_no', 'product_id', 'assay_type', 'valid_from', 'expiry_date', 'is_active', 'last_modified', … -
Half of the dropdown is hidden
I made a django app with a navbar. On the right corner, it has a user area with some things, like profile and logout area. This user area is a dropdown, and when it's activated it goes outside the navbar. dropdown error I tried several things, like adding "dropdown-menu-right" but nothing worked, it's probably some stupid mistake I made and I can't figure it out. Can you help me ? navbar <nav class="navbar navbar-expand-lg navbar-dark bg-dark"style="width: 100%;" id="navbar"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'home' %}">Plataforma</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> {% if user.is_authenticated %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Documentos </a> <ul class="dropdown-menu mr-auto"> <a class="dropdown-item" href="{% url 'carregar-documentos'%}">Carregar</a> <hr class="dropdown-divider"> <a class="dropdown-item" href="{% url 'download-documentos'%}">Download</a> </ul> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Dados</a> <ul class="dropdown-menu dropdown-menu-right"> <a class="dropdown-item" href="{% url 'list_triturador'%}">Triturador</a> <hr class="dropdown-divider"> <a class="dropdown-item" href="{% url 'atualizar'%}">Atualizar</a> {% url 'list_triturador' as sitio %} {% if request.path == sitio %} <a class="dropdown-item" href="{% url 'triturador_csv'%}">Exportar Excel</a> {% endif %} {% else %} {% endif %} </ul> </li> </ul> <!-- Dropdown Error --> <ul … -
How to bypass "yes" on Django crontab in the function
I have a Django application with dbbackup library and crontab library that will take the database backup every one hour. https://django-dbbackup.readthedocs.io/en/master/index.html https://pypi.org/project/django-crontab/ In order to restore the back up file. I have to use this command in the shell manually. python manage.py dbrestore However, I want to schedule this task by using crontab. Here is my code. ` from django.core.management import call_command def restore_scheduled_job(): try: call_command('dbrestore') except: pass ` This will not work since after the "python manage.py dbrestore" command, I have type "y" in order to process the command. How can I bypass this yes in the function? I researched in the documentation but I couldn't find any solutions. -
Why does my Heroku app say my app is using Postgresql?
Since Heroku is removing its free tier, I'm currently in the process of upgrading. However it says that my web app will be turned into an eco dyno, and my postgresql will be switched to "mini". I do not use any database in my app, and am not sure why it shows up. Will Heroku shut down my app if I don't pay an additional $5 a month for the database or can I just pay for the eco dyno? I tried to look at the Heroku knowledge articles and stack overflow but could not find the specific answer I'm looking for. -
How to send javascript variable to Django backend?
I have the following variable, inside of a <script> tag in my /dashboard/ path: var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds(); And I have this model I want to update: class UserDetail(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True,) totallearningtime = models.IntegerField(default = 0,) I want to be able to add the current totallearningtime to my javascript variable and update the model accordingly. Here is my /dashboard/ view: def dashboard(request,): user = request.user user_details = UserDetail.objects.get(user=user) context = { "total_learning_time": user_details.totallearningtime, } return render(request, 'dashboard.html', context) As you see, I get the total_learning_time, but I am not sure how to update it with my javascript variable. I'm not sure if my URL is needed, but here it is: path('dashboard/', views.dashboard, name = "dashboard"), Can someone please help me so that I can pass my javascript variable into my model? -
How to do mutation query in GraphQL in Django?
# Model class Customer(models.Model): name = models.CharField(max_length=150) address = models.CharField(max_length=150) # Node class CustomerNode(DjangoObjectType): class Meta: model = Customer interfaces = (relay.Node,) # Mutations class CreateCustomerMutation(relay.ClientIDMutation): class Input: name = graphene.String(required=True) address = graphene.String() customer = graphene.Field(CustomerNode) @classmethod def mutate_and_get_payload(cls, root, info, **input): customer_instance = Customer( name=input.name, address=input.address, ) customer_instance.save() return CreateCustomerMutation(customer=customer_instance) I have gone through documentation and other tutorials but can't seem to figure out how to execute a mutation query. I've tried # Query 1 mutation { createCustomer(name: "John", address: "Some address") { id, name } } # Query 2 mutation { createCustomer(input: {name: "John", address: "Some address"}) { id, name } } but it doesn't work and shows error - # Query 1 "Unknown argument 'name' on field 'Mutation.createCustomer'." "Unknown argument 'address' on field 'Mutation.createCustomer'." # Query 2 "Unknown argument 'input' on field 'Mutation.createCustomer'." What am I missing? What is the correct syntax/expression to do so? -
How to restart celery by cron
Celery is installed inside the docker. I need to reboot it on schedule. How can I do this? It is necessary that the tasks performed complete their work. Or how to make the stop command for the docker container service wait for the completion of celery like this: app.conf.beat_schedule = { 'celery_restart': { 'task': 'app.tasks.celery_restart', 'schedule': crontab(hour=2) } } my docker-compose.yaml services: back: ... ... celery: container_name: my_celery restart: always command: celery -A core worker -P threads -B -l info -c 100 requirements: django==4.1 celery==5.2.7 I can't use systemctl and change the project structure -
How can I reset password in django by sending code to the user?
How can I implement password reset in django, in a safe and secure way by sending a code to the user's email/phone? Is there any package for this purpose? I emphasis that I want to do this by sending a code to the user, not a link or anything else. Something like what microsoft or google accounts does. I've searched a lot for this problem but I never found a proper solution. -
Checking if a value exists in one template so that I can create a notification in another template
I have a bootstrap card that holds a list of information and within that information there is a boolean value. If that value is true, I'd like to show some kind of notification on the card. Here is what it looks like So if in one of those links there is a value that is true, I'd like something notifying the user that everything is all good and if a value is false, let them know something is wrong. Maybe like a thumbs up and thumbs down from font awesome or something(not important right now). Here is my template that holds that information <link href="{% static 'css/styles.css' %}" rel="stylesheet" /> <div class="card"> <div class="card-header text-dark"> <div class ="card-body"> <div class="table-responsive"> <table class="table table-bordered"> <thead class = "table-light"> <tr class="text-center"> <th>Location</th> <th>RSU ID</th> <th>Install confirmed</th> <th>Winter mode</th> <th>Date created</th> <th>Created by</th> <th>Date updated</th> <th>Updated by</th> </tr> </thead> <tbody> <tr class="text-center"> <td>{{object.location}}</td> <td>{{object.rsu_id}}</td> {% if object.instln_confirmed %} <td><i class="fas fa-check fa-2xl text-primary"></i></td> {% else %} <td><i class="fas fa-x fa-2xl text-danger"></i></td> {% endif %} {% if object.winter_mode %} <td><i class="fas fa-check fa-2xl text-primary"></i></td> {% else %} <td><i class="fas fa-x fa-2xl text-danger"></i></td> {% endif %} <td>{{object.date_created}}</td> <td>{{object.created_by}}</td> <td>{{object.date_updated}}</td> <td>{{object.updated_by}}</td> </tr> </tbody> </table> </div> </div> … -
AWS Pipeline fails when running "container_commands"
Trying to created a CI/CD with AWS Elastic Beanstalk, GitHub and Django. Everything else looks quite fine till I run the migration command. It basically fails when the container commands gets executed. I've tried to run it in different ways but nothing works to me. Try to run the pipeline without the commands and it works fine but of course the app itself won't work without running the migrations . So after retrieving the logs it fails here at the container_commands: option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: project.settings "PYTHONPATH": "/opt/python/current/:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: project.wsgi:application NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:environment:proxy:staticfiles": /html: statichtml /static-files: static-files /media: media-files ** container_commands: 10_deploy_hook_permissions: command: | sudo find .platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \; sudo find /var/app/staging/.platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \; ** This command will execute a script which is this : #!/bin/sh source /var/app/venv/staging-LQM1lest/bin/activate python /var/app/current/manage.py collectstatic --noinput python /var/app/current/manage.py migrate But this is not the issue, Can anyone help pls ?? -
how to call a node js function inside a django page?
i have one web page created in Django , another web page created in node and express js (a function is there to print some barcodes via a barcode printer ) can i call the function from my Django page i am unable to find any idea about how to do whether it is possible or not -
TypeError at /admin_update/2/ BaseForm.__init__() got an unexpected keyword argument 'instance'
I'm trying to update my table view. I passed primary key into update_requests.html so that I can pre-fill the form with the model with the primary key. However, I think it is the problem with model. When I try to access update_requests.html, it shows the error as descripted in the title. Can someone help me with this? urls.py ` path('admin_update/<str:pk>/', views.AdminUpdateRequests, name='admin_update'), ` views.py ` def AdminManageRequests(request): lessons = Lesson.objects.all() return render(request,'admin/manage_requests.html',{'lessons':lessons}) def AdminUpdateRequests(request, lesson_id): lesson = Lesson.objects.get(pk=lesson_id) form = StudentRequestForm(request.POST or None, instance=lesson) context = { 'lesson':lesson, 'form':form } return render(request, 'admin/update_requests.html',context) ` models.py class Lesson(models.Model): lesson_id = models.AutoField(primary_key=True) lesson_name = models.CharField(max_length=255) student = models.ForeignKey(User,on_delete=models.DO_NOTHING,related_name='studying') teacher = models.ForeignKey(User,on_delete=models.CASCADE, related_name='teaching') start_time = models.DateTimeField(default=timezone.now) interval = models.IntegerField(default=0) duration = models.IntegerField(default=0) created_at = models.DateTimeField(default=timezone.now, blank=True) updated_at = models.DateTimeField(default=timezone.now, blank=True) is_request = models.BooleanField(default=True) number = models.IntegerField(default=-1) price = models.IntegerField(default=-1, blank=True) manage_requests.html ` {% extends 'admin/admin_home_base.html' %} {% block admin_content %} <div> <h3 class="display-8" style="text-align:center"> Admin Lesson Request Management </h3> <hr class="my-4"> <p style="text-align:center"> You can view fulfilled and unfulfilled lesson requests. </p> <p class="lead" style="text-align:center"> {% include 'admin/partials/fulfilled_lessons.html' %} <br> {% include 'admin/partials/unfulfilled_lessons.html' %} </p> </div> {% endblock %} lessons_table_base.html ` ` <div class="card"> <div class="card-header"> <h5 class="card-title">{% block card_title %}{% endblock %}</h5> … -
Django Method Field return Serializer with Hiperlinked field
How can I have a method Field that returns a serializer that has a Hyperlinked field? For example, the Object-1 serializer looks like: from rest_framework import serializers class Object1Serializer((serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='api:object-detail') name = serializers.CharField(max_length=50) and Objec2: class Object2Serializer(UserSerializer): objects1 = serializers.SerializerMethodField() def get_objects1(self, obj): objects1 = models.Objects1.objects.get_queryset_by_user(user=obj) serializer = Object1Serializer(objects1, many=True) # serializer.context.update({'request': self.context['request']}) return serializer.data There is a problem here: the url field in Object1 needs a context to construct the url of the field, but I don't know how to get around this. I tried updating the Object1 serializer context, but it doesn't seem to work. -
While using Django GraphQL Auth package, I am able to achieve all the functionality but somehow the passwordReset mutation is always timing out. Why?
I have a GraphQL API in Django which uses the Django GraphQL Auth package for implementing auth related mutations. All of my code works as it did before except for the passwordReset mutation. I have a timeout at 30 seconds in my Gunicorn server and always the passwordReset mutation timesout. I am not seeing any errors in the log. I tried running it locally and the same code seems to work just fine. This seems unusual considering I don't see a reason why a passwordReset should take such a long time to resolve. I am stuck here for a while and don't have any leads on this. Help! -
SQL query to filter on group of related properties
I have a recurring problem in SQL queries, that I haven't been able to solve elegantly, neither in raw SQL or the Django ORM, and now I'm faced with it in EntityFramework as well. It is probably common enough to have its own name, but I don't know it. Say, I have a simple foreign key relationship between two tables, e.g. Book 1 <- * Tag A book has many tags and a tag has one book, i.e. the Tag table has a foreign key to the book table. Now, I want to find all books that have "Tag1" and "Tag2". Raw SQL I can make multiple joins SELECT * FROM books JOIN tags t1 on tags.book_id = books.id JOIN tags t2 on tags.book_id = books.id WHERE t1.tag = 'Tag1' AND t2.tag = 'Tag2' Cool, that works, but doesn't really seem performant Django In django, I could do something similar Book.objects.filter(tags__tag="Tag1").filter(tags__tag="Tag1") Changing filters like that will cause the extra joins, like in the raw SQL version EntityFramework LINQ I tried chaining .Where() similar to changing Django's .filter(), but that does not have the same result. It will build a query resembling the following, which will of course return nothing, because …