Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make calculations after requesting with M2M fields (DRF)
class Product(models.Model): name = models.CharField(max_length=255) ht = models.CharField(default=0) wd = models.CharField(default=0) len = models.CharField(default=0) class Parcel(models.Model): product_list = models.ManyToManyField(Product) class ParcelSerializer(serializers.ModelSerializer): class Meta: model = Parcel fields = '__all__' class ProductSerializer(serializers.ModelSerializer): product_volume = serializers.ReadOnlyField() class Meta: model = Product fields = '__all__' class ParcelCreateView(generics.CreateAPIView): queryset = Package.objects.all() serializer_class = PackageSerializer class ParcelListView(generics.ListAPIView): serializer_class = ParcelSerializer class ProductCreateView(generics.CreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer class ProductListView(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer My output is : [ { "id": 1, "products": [ 1 ] }, { "id": 2, "products": [ 1, 2 ] } ] How can I get product id and product volume as below? I didn't understand what to do because it's ManyToManyField. After the request comes, how can I get product ids from the body and calculate their volume [ { "id": 1, "products": [ 1 : Result #Volume of ID : 1 Product (wd*ht*len) ] }, { "id": 2, "products": [ 1 : Result #Volume of ID : 1 Product (wd*ht*len), 2 : Result #Volume of ID : 1 Product (wd*ht*len) ] } ] -
Django: complex order by and filter by from many relations query with nested models
What I want to achieve: I want list of [ { "location": "Loc 1", "session": [ { "start": "2021-01-01", "counts": 600, "details": [ { "id": 13, "length_max": 21, "length_min": 15, "length_avg": 16, "length_std": 19, "is_active": false, "type": "dog" } ] } ] }, { "location": "Loc3", "session": [ { "start": "2021-01-01", "counts": 500, "details": [ { "id": 15, "length_max": 19, "length_min": 16, "length_avg": 16, "length_std": 19, "is_active": false, "type": "dog" } ] } ] } ] My Viewset is class AquaticFilter(FilterSet): type_filter = filters.CharFilter(method="filter_by_type") def filter_by_type(self,queryset,name,value): queryset = queryset.filter(session__details__type=value).distinct() return queryset class SessionModelViewSet(ModelViewSet): queryset = Session.objects.all() serializer_class = SessionSerializers filter_backends = (DjangoFilterBackend,) filter_class = SessionFilter I am trying to filter based on type, but am not able to fetch what I need. The out I am getting is [ { "location": "Loc 1", "session": [ { "start": "2021-01-01", "counts": 600, "details": [ { "id": 13, "length_max": 21, "length_min": 15, "length_avg": 16, "length_std": 19, "is_active": false, "type": "dog" } ] }, { "start": "2021-01-01", "counts": 600, "details": [ { "id": 7, "length_max": 39, "length_min": 25, "length_avg": 25, "length_std": 27, "is_active": true, "type": "cat" }, { "id": 19, "length_max": 39, "length_min": 25, "length_avg": 25, "length_std": 27, "is_active": false, "type": "cat" } ] … -
Django: django.db.utils.IntegrityError: null value in column "post_id" of relation "posts_comment" violates not-null constraint
I am getting this error django.db.utils.IntegrityError: null value in column "post_id" of relation "posts_comment" violates not-null constraint DETAIL: Failing row contains (16, Just a check, 2021-07-20 14:13:15.751175+00, , null,). This is my comment model class Comment(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post_comments") reply = models.ForeignKey('Comment', null=True, related_name='replies', blank=True, on_delete=models.CASCADE) content = models.TextField(max_length=1000) timestamp = models.DateTimeField(auto_now_add=True) This is my serializer class CommentSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) user = serializers.ReadOnlyField(source="user.username") content = serializers.CharField() comment_id = serializers.PrimaryKeyRelatedField(source='reply', queryset=Comment.objects.all(), write_only=True, required=False) def create(self, validated_data): user = self.context['request'].user content = validated_data['content'] comment = Comment(user=user, content=content) comment.save() return comment This is my view function def post(self, *args, **kwargs): post = get_object_or_404(Post, slug=self.kwargs['slug']) serializer = CommentSerializer(data=self.request.data, partial=True, context={'request': self.request}) if serializer.is_valid(): comment_id = self.request.POST.get('comment_id') comment_qs = None if comment_id: comment_qs = Comment.objects.get(id=comment_id) serializer.save(post=post) else: serializer.save(post=post) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Can someone help to solve this? Thanks note: I don't want to use ModelSerializer. want to learn to use Serializer. -
ImportError: cannot import name 'faker' from partially initialized module 'faker' (most likely due to a circular import)
from random import randint from faker import faker from quiz.models import Quiz, Question, Choice import random import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'schoolauthquiz.settings') django.setup() fakegen = faker() name = ['HTML', 'CSS', 'JavaScript', 'MySQL','Python', 'jQuery', 'Bootstrap4','Math'] fake_num_questions = fakegen.randint(1, 10) def add_quiz(): q = Quiz.objects.get_or_create( quiz_title=random.choice(name), num_questions=fake_num_questions)[0] q.save() return q def populatequestion(N=10): for entry in range(N): quiz = add_quiz() fake_question_text = fakegen.question_text() # fake_question_num = fakegen.question_num() fake_answer = fakegen.answer() fake_explanation = fakegen.explanation() # fake_question = fakegen.question() fake_choice_text = fakegen.choice_text() fake_correct = fakegen.correct() Q = Question.objects.get_or_create(quiz=quiz, question_text=fake_question_text, question_num=fake_num_questions, answer=fake_answer, explanation=fake_explanation)[0] """ question_num=num_questions question=questionid """ ch = Choice.objects.get_or_create( question=Q, correct=fake_correct, choice_text=fake_choice_text)[0] if name == 'main': print("populating script!") populatequestion(10) print("populating populatequestion Complate!") ` -
Django thinks my model object dosent exist
django thinks my model object doenst exist. The code is working fine because it behaves like its supposed to for another user. i get this enter image description here BUt its there in the admin page.enter image description here It be because I can migrate since it thinks there is a feild that dosent exist with a null param that wont work. I deleted it tho and the ENTIRE model that was associated with it. enter image description here See? its not there. enter image description here can anyone tell me what is happeing here? -
Edit the value of an attribute inside a serializer Django Rest
What I'm trying to do is changing the value of an attribute in the serializer (seemed like the appropriate place to change it). "unsupported operand type(s) for *: 'int' and 'DeferredAttribute'". This is the error that I'm recieving when doing it my way. Any assistance would be most welcomed. Models: class Product(models.Model): price =models.IntegerField name=models.CharField(null=True) In a different app I have the other model class Order_unit(models.Model): amount=models.IntegerField price=models.IntegerField product=models.ForeignKey(Product) Serializer: from order.models import * from product.models import * class OrderUnitSerializer(serializers.ModelSerializer): price= serializers.SerializerMethodField('get_price') class Meta: model = Order_unit fields = ['order', 'product', 'amount', 'price'] def get_price(self,Order_unit): price= Order_unit.amount*Product.default_price return price -
html id value not changing
I am trying to update the applied candidate selection status using ajax but I am having issues with the select tag name attribute which is not changing its ID value when I am iterating through, it's showing the same id in every iteration my template <th>skills req</th> </tr> {% for val in applicants %} <tr> <td>({{val.user.id}}){{val.user.username | capfirst }}</td> <td>{{val.apply_date}}</td> <td> <select class="status_select" name="status" id="{{val.user.id}}"> <-- even though here it should be changing it <option value="onhold">Onhold</option> <option value="selected">Selected</option> <option value="rejected">Rejected</option> </select> </td> <td> <b>{{val.job_post.job_type}}</b> </td> <td>{{val.job_post.title}}</td> <td>candidate skills</td> </tr> {% endfor %} </table> jquery snippet $("body").on("change", ".status_select", function (e) { e.stopPropagation(); console.log($(this).val()); id = $(".status_select").attr("id"); console.log(id); console.log("working"); $.ajax({ url: "/users/status_change/", type: "GET", contentType: "application/json", dataType: "json", data: { id: id, selected_val: $(this).val(), }, success: function (data) { console.log(data); }, error: function (error) { console.log(error); console.log("calling from error"); }, }); }); I mean to say like this (id value stuck at 4) id-> 4 [20/Jul/2021 19:31:10] "GET /users/status_change/?id=4&selected_val=rejected HTTP/1.1" 200 19 selected id-> 4 [20/Jul/2021 19:31:16] "GET /users/status_change/?id=4&selected_val=selected HTTP/1.1" 200 19 rejected id-> 4 [20/Jul/2021 19:31:18] "GET /users/status_change/?id=4&selected_val=rejected HTTP/1.1" 200 19 onhold id-> 4 [20/Jul/2021 19:31:19] "GET /users/status_change/?id=4&selected_val=onhold HTTP/1.1" 200 19 onhold id-> 4 [20/Jul/20 my view def status_change(request): if request.method=='GET': … -
How to I simply set a default url parameter in a django redirect?
So I have an app, that people login and it shows them a list of data. We recently made some filters and it would be nice if some of the filters were just on by default, which is simple in the code but I want the url to reflect the GET variables Im using for user sanity. So, I have this: #settings.py ACCOUNT_LOGIN_REDIRECT_URL = "status_dashboard" and #urls.py path( r"dashboard/?status=in_progress", DashboardView.as_view(), name="status_dashboard"), it would work but it escapes the ? in the url for safety, there must be a way to do this thats dead simple but I can only find things on passing POST variables to the view, which I dont need. -
Django Query / Template Language Confusion
I have an issue with my code and I am not sure why it works this way. I have a model which is an order, and then order item which is like a link in between the product and the order itself. The issue is I am creating a completed order page for my website in order for people to leave a review on a product. I originally used a get query and then was able to connect through to other tables with the template language object.items.all because I am using a many to many field. But with multiple things ordered my get query returns more than 1 object and an error is produced. To solve this I then tried to switch the query to .filter() but then I am unable to use object.items.all in the template and I am confused as to why? I will link the models and template. Sorry for this terrible explanation, I hope the models clear up any misunderstanding. Models class Product(models.Model): name = models.CharField(max_length=120) shortened_name = models.CharField(max_length=50) date_of_creation = models.CharField(max_length=20, null=True) history = models.CharField(max_length=255) price = models.DecimalField(max_digits=9, decimal_places=2) discount_price = models.FloatField(blank=True, null=True) style = models.CharField(max_length=50) artist = models.ForeignKey(Artist, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to='images', null=True) … -
Since i removed sessionid, django is not creating new one
While i was creating shopping cart which depends on sessionid included in cookie files I once removed sessionid in my browser to test something and then i realised that django don't want to recreate new one. I was looking for solution in internet but i didn't found any equal problem to my and solution to it. By looking on the django docs. i wrote to setting.py hoping that it would help: SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_COOKIE_HTTPONLY = True but still sessionid in cookies doesn't occur. I read post that sessionid should be generated by django while there is request which require sessionid, and it would be in my situation solution on this problem but in the context_processors.py I wrote that i require sessionid globally: def basket(request): try: customer = request.user.customer except: device = request.COOKIES['sessionid'] customer, created = Customer.objects.get_or_create(device=device) order, created = Order.objects.get_or_create( customer=customer, complete=False) return { 'order': order, } And beacouse of the context_processors sends request for sessionid and it can't get one, this error occurs: Any solutions? -
WTF is up with Django?
So my template is throwing this error:This is the error But I KNOW that the object exists. I check the one in question in the photo: This is the object it says is there It wont let me migrate because it thinks that there is a "Post" model with a null field it cant fix: Says the Post model field TAGS is there But I freaking deleted and still got the same thing. So I tried deleting the WHOLE post model and yet it thinks its still there: nope...not there. So it thinks something is gone that isnt and that something is there that is gone. WHAT THE FUUUUUUUUUUUUUUUCCKKK!!!?!?!?!?!?!?!?!??! -
filter to pagination django
implemented sorting and pagination on the product page, but sorting gets confused when moving to the next page. How do I apply a filter to all pagination pages?and i got smth weird with dropdown selection: after moving to next pages it starts act like crazy,after choosing a filter and refreshing the page, it returns to the default value and seems to be changing places (exmp: $$-$ -> $-$$ and vice versa , and i must guess who is who :) ) template <div class="product-sorting d-flex"> <p>Sort by:</p> <form name="selectForm" action="{% url 'shop' %}" method="get"> <label for="orderby"></label> <select name="orderby" id="orderby" onchange="selectForm.submit();"> <option value="price">price: $$ - $</option> <option value="-price">price: $ - $$</option> </select> <input type="submit" class="d-none" value="submit"> </form> </div> views class Shop(ListView): template_name = 'essense/shop.html' context_object_name = 'items' paginate_by = 9 allow_empty = False model = Item def get_context_data(self, *, object_list=None, **kwargs): ***context*** def get_ordering(self): return self.request.GET.get('orderby', ) -
Get separate serializer response for each nested serializer
Stuck with serializer where I need to have serialized response based on the nested serializer. Models.py : class Parent(models.Model): name = models.CharField(max_length=50) class Child(models.Model): parent = models.ForeignKey(Parent, related_name='children') child_name = models.CharField(max_length=80) Serialziers.py class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = '__all__' class ParentSerializer(serializers.ModelSerializer): child = serializers.SerializerMethodField() def get_child(self, obj): childs = Child.objects.filter(parent=obj) return ChildSerializer(childs, many=True).data class Meta: model = Parent fields = '__all__' I am getting output like below where I am getting nested childs: { id : 1, name : "Parent1", child: [ 0: {id : 1, child_name : "child1"} 1: {id : 2, child_name : "child2"} ] } But for some business purpose I need output to be something like below, where serializer should be based on child. i.e. for each child there should be separate Parent serializer. Doesn't matter if it has same id and other fields. : { 0:{ id : 1, name : "Parent1", child: [ 0: {id : 1, child_name : "child1"} ] } 1:{ id : 1, name : "Parent1", child: [ 0: {id : 2, child_name : "child2"} ] } } Also please let me know if I can filter based on the child serializer. i.e. childs I will be passing … -
Not able to activate debug in VS-code for Django project (Django in virtual environment)
I have an issue running the Debug environment for Django application in VS-code: my python is not in the virtual environment, while my django is. Therefore, the solution I see everywhere with adding to the launch.json settings the line "pythonPath": "${workspaceRoot}/.venv/bin/python2.7", does not fit, and I end up having the following error: Exception has occurred: ImportError Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? When working on the application, I launch the setting environement using the following command: .\venv\Scripts\activate.ps1 Can anyone help me out to declare my virtual environment the proper way in the launch.json file? -
How to change serializer field name with python forbidden character
I need to have a serializer that returns data with illegal character inside dictionary key, what I would like is : class MyModel(models.Model): my_field = model.TextField() ... serializer = MySerializer(django_object) serializer.data # returns {'my-field' : "value"} I have tried using serializers.SerializerMethodField but target field name must be Python valid. class MySerializer(serializers.Serializer): my-field = serializers.SerializerMethodField(method_name="get_my_field") # ^ this fail to be interpreted by Python def get_my_field(self, obj): return obj.my_field using source as an argument to any Serializer fails for the same reason. -
Reverse for 'customer' with arguments '('',)' not found. 1 pattern(s) tried: ['customer/(?P<pk>[^/]+)/$']
I am getting this error when I'm trying to pass a dynamic URL in Django. please Help. dashboard.html {% for i in customers %} <tr> <td><a class="btn btn-sm btn-info" href="{% url 'customer' customer.id %}">View</a></td> <td>{{i.name}}</td> <td>{{i.phone}}</td> </tr> {% endfor %} urls.py urlpatterns = [ path('', views.home, name="home"), path('products/', views.products, name="products"), path('customer/<str:pk>/', views.customer, name="customer"), ] views.py def customer(request, pk): customer = Customer.objects.get(id=pk) orders = customer.order_set.all() total_order = orders.count() context = {'customer': customer, 'orders': orders, 'total_order':total_order} return render(request, 'accounts/customer.html', context) -
Djang select and delete posts
I am making a blog based on Django on guides. I have a list of posts that you can change and delete. How to make it possible to select multiple posts and delete? I don't even know which side to approach the problem. -
using `django-push-notifcations` package; How does `active` state change on the `push_notifications_gcmdevice` table.; getting sent messages count
I use django with the django-push-notifications package to send push notifications with the Legacy FCM. When sending push notifications, I would like to know which users did/didn't get the message. Due to the way my DB is built and the messaging logic I'm using, I can not just use the devices.send_message() func to send to all users at once. That would have been great, since I would get the success count in the HTTP Response like this: { "multicast_id": 108, "success": 1, "failure": 0, "results": [ { "message_id": "1:08" } ] } Instead I need to loop through a queryset of users and send each one separately, by calling device.send_message(). Now, I know I can save the response from each message and tally them with a counter of some sort, but that really won't work as I use a separate thread to deal with sending the messages, and waiting for thousands of messages to send is going to defeat the purpose of using a thread. Currently I use this code after sending the notifications to know how many were sent/not sent: all_users = queryset.count() active_fcm = GCMDevice.objects.filter(user_id__in=queryset.values_list('id', flat=True), active=True).count() return Response({ 'sent': active_fcm, 'not_sent': all_users - active_fcm }, status=status.HTTP_201_CREATED) I … -
Creating Relational database with user model in Django. I think i have created relational database but i don't know whats going wrong
I think i have successfully created relation between user model and another table called shop_details but the data is not been inserted. i don't know what is going wrong. the code is here. models.py from django.db import models from django.contrib.auth.models import User class Shop_Details(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) shop_name = models.CharField(max_length=50) shop_street = models.TextField() shop_area = models.TextField() city = models.CharField(max_length=50) state = models.CharField(max_length=50) pin_code = models.TextField() my views.py is here views.py def shop_detils(request): if request.method == "POST": shop_name = request.POST['shop_name'] shop_street = request.POST['shop_street'] shop_area = request.POST['shop_area'] city = request.POST['city'] state = request.POST['state'] pin_code = request.POST['pin_code'] if(len(str(pin_code))!=6): messages.info(request,"please provide a valid address pin-code") print("niceee...........................") return render(request,'shop_details.html') else: if(is_number(int(pin_code))): shop = Shop_Details(shop_name=shop_name,shop_street=shop_street,shop_area=shop_area,city=city,state=state,pin_code=pin_code,user=request.user) shop.save() messages.info(request,"Shop Details Updated") shop_data = Shop_Details.objects.filter(user = request.user) print(shop_data[1]) print("congrats...........................") return redirect('home',{'data':shop_data}) else: messages.info(request,"please provide a valid address") print("nice2222222222222222222222222") return render(request,'shop_details.html') else: return render(request,'shop_details.html') my shop_details.html is here shop_detsils.html enter code here {% extends 'layout.html' %} {% csrf_token %} {% if user.is_authenticated %} {% csrf_token %} {% load static %} {% csrf_token %} <meta name="viewport" content="width=device-width, initial-scale=1"> {% csrf_token %} <body align="center"> {% csrf_token %} {% csrf_token %} {% csrf_token %} {% block content %} <form action="shop_detils" method="POST"> {% csrf_token %} <div align="center" class='resp_code frms'> {% csrf_token %} <p … -
How to get data from the database and assign it to a serializer Django
I'm working on a django rest program. I have two apps, product and order. Now on the order app, i have two models, order and order unit. What I need to do is figure out a way that when I create an order and an order unit (they should be created together), I need to get the price from the product to display on the order unit when I choose the product there. So for example, I choose the product and I want the price of that product to be automatically filled in, hope I was clear enough. Now this is the code and what I've tried so far. Models of order: class Order(models.Model): code = models.IntegerField(unique=True) code_year = models.IntegerField date_registered = models.DateTimeField(default=timezone.now) customer = models.ForeignKey(Customer, related_name='customer_orders', null=True, on_delete=models.CASCADE) creator = models.ForeignKey(User, related_name='orders', null=True, on_delete=models.CASCADE) class Order_unit(models.Model): order = models.ForeignKey(Order, related_name='orderunits_orders', null=True, on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='orderunits_products', null=True, on_delete=models.CASCADE) amount = models.IntegerField price = models.IntegerField Serailizers: class OrderUnitSerializer(serializers.ModelSerializer): class Meta: model = Order_unit fields = ['order', 'product', 'amount', 'price'] class OrderSerializer(serializers.ModelSerializer): orderunits_orders = OrderUnitSerializer(many=True) class Meta: model = Order fields = [ 'id', 'code', 'code_year', 'date_registered', 'customer', 'creator', 'orderunits_orders' ] Views: class OrderListCreateAPIView(ListCreateAPIView): queryset = Order.objects.all() serializer_class = OrderSerializer permission_classes … -
Can I include two different urls to the same url pattern? Example [ path('api/', include('quiz.urls')), path('api/', include('user.urls')) ]
127.0.0.1:8000/api/ Is containing only urls from the second app, but I linked both url modules to the same pattern. Is it even possible to do that? first app: from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'users', viewset=views.UserProfileViewSet) urlpatterns = [ path('', include(router.urls)) ] second app: from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'question', viewset=views.QuestionViewSet) router.register(r'review', viewset=views.ReviewViewSet, basename='review') urlpatterns = [ path('', include(router.urls)) ] main: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('quiz.urls')), path('api/', include('user.urls')) ] -
Django formset - validate_min=False being ignored
I'm pretty new here, this is my first question but hopefully someone will be able to help me. I've made a inlineformset in Django. I've set "min_num" at 6 with valide_min=False, but when I fill in less than 6 forms in the formset, the data is not inserted in the database, it seems like the formset.is_valid() is False. Can someone help me out? (filtered) code below. Thanks! views.py from django import forms from django.forms import inlineformset_factory from django.shortcuts import render, redirect from actie import Actie from inzetlijst import Inzetlijst from medewerker import Medewerker def index(request, actie_id): actie = Actie.objects.get(pk=actie_id) LanguageFormset = inlineformset_factory(Actie, Inzetlijst, fields=('taaknummer', 'voertuig', 'medewerker'), extra=2, can_delete_extra=False, min_num=6, validate_min=False) if request.method == 'POST': formset = LanguageFormset(request.POST, instance=actie) if formset.is_valid(): formset.save() return redirect('create_inzetlijst', actie_id=actie.id) formset = LanguageFormset(instance=actie) for form in formset: form.fields['voertuig'].empty_label = "" form.fields['medewerker'].queryset = Medewerker.objects.exclude(youforce=0).order_by('team', 'achternaam') form.fields['medewerker'].empty_label = "" try: form.fields['DELETE'].widget = forms.CheckboxInput() form.fields['DELETE'].label = 'Wissen' except: pass return render(request, 'odin/actie/inzetlijst_aanmaken_form.html', {'formset': formset}) template.html {% block content %} {% block content_form_title %} {% endblock content_form_title %} {{ form.non_field_errors }} <form action="" method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset.forms %} <div class="row"> <div class="col s4 m2"> {{ form.taaknummer.errors }} <label for="id_taaknummer">{{ form.taaknummer.label }}</label> {{ … -
Django | Annotate objects to query
I am currently struggling to figure out how to deal with the following problem: Imagine I got this two models: class author(models.Model): name = models.CharField(mac_length=50) ... and class book(models.Model): author = models.ForeignKey('author', on_delete=models.CASCADE) ... Now I want to create a view which list all authors with all their book's. This could look something like this: Joanne K. Rowling: Harry Potter and the Philosopher's Stone ... J. R. R. Tolkien: The Hobbit ... Question: How should the Django Query look like to access the Books in the template? ` authors = authors.objects.all() This gives me the set for the authors, but not their belonging books. Is there a way to annotate or aggregate Dict's to the Queryset? I feel like this beeing Rookie stuff, but it would still be nice if you could help me out. -
DRF - how to pass a value to a serializer, omitting user's request body
Imagine we have such a simple model: class Tag(models.Model): owner = models.ForeignKey(to=User, on_delete=models.CASCADE) title = models.TextField() and a serializer for it: class TagSerializer(serializers.ModelSerializer): owner = serializers.PrimaryKeyRelatedField( many=False, write_only=True, queryset=User.objects.all(), ) title = serializers.CharField() class Meta: model = Tag fields = ("owner", "title") validators = [ UniqueTogetherValidator( queryset=Tag.objects.all(), fields=["owner", "title"], message="", ) ] Well, the task sounds quite simple: how to pass the owner instance (or it's primarykey) from a view, but to keep the field invisible for a user? I mean, it hasn't be rendered by drf-yasg, and a user's request like {"owner": 1, "title": "cats"} must be discarded because of unknown field "owner". Is there only a single way - to pass the value via context, and then rewrite serializer's validate & update & create methods to support it? I hope you know better approaches. -
profiling clery tasks and functions in django
I'm working on a Django application with some algorithmic routines that I manage them using celery. I have a lot of DB queries in my algorithms and obviously, query optimization is really critical for performance. However, I can't find any packages for celery task profiling, just like Django debug toolbar or Django silk that works on HTTP requests. Is there a solution for investigating a particular function in my code (e.g logic())? I need some reports like execution time, similar or duplicate queries and etc.