Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page with a dynamic number of forms, each form for each table row
The company has workers performing various activities during a day. Each activity has start_time and finish_time. It is usual that workers forget to beep the end of activity (finish_time) and that's because there is a stored procedure read_unended time_from time_to which reads records between time_from and time_to which has not finish_time (is NULL). For example id name day start_time finish_time place activity 38 Thomas 2021-12-03 2021-12-03 08:51:38.000 NULL p1 a1 28 Charles 2021-12-02 2021-12-02 12:29:03.000 NULL p2 a2 49 John 2021-12-06 2021-12-06 11:59:48.000 NULL p3 a3 68 Jessie 2021-12-08 2021-12-08 10:55:12.000 NULL p4 a4 82 Susanne 2021-12-10 2021-12-10 12:38:03.000 NULL p5 a5 There is a form in (forms.py) class FromToForm(Form): start_date = DateField(widget=AdminDateWidget()) start_time = TimeField(widget=AdminTimeWidget()) end_date = DateField(widget=AdminDateWidget()) end_time = TimeField(widget=AdminTimeWidget()) There is a view in (views.py) which displays such a table. def ending(req): from_to_form = FromToForm() result = [] context = { 'form': from_to_form, 'result': result } if req.method == "POST": from_to_form = FromToForm(req.POST) if from_to_form.is_valid(): start = datetime.combine(from_to_form.cleaned_data['start_date'], from_to_form.cleaned_data['start_time']).isoformat() end = datetime.combine(from_to_form.cleaned_data['end_date'], from_to_form.cleaned_data['end_time']).isoformat() with connections["mssql_database"].cursor() as cursor: cursor.execute("EXEC read_unended @dt_od='%s', @dt_do='%s'" % (start, end)) result = cursor.fetchall() context['result'] = result return render(req, 'ending.html', context) else: return render(req, 'ending.html', context) else: return render(req, 'ending.html', context) and an associated … -
Django / Cloudrun / Docker migration failed
I try to create a Django project on Google Cloud Plateform (Cloudrun). I'm following the official tutorial here : https://codelabs.developers.google.com/codelabs/cloud-run-django#7 As I'm trying to execute my first basic migration : gcloud builds submit --config cloudmigrate.yaml \ --substitutions _REGION=$REGION I have this error : Step #2: ModuleNotFoundError: No module named 'app' Here's my project's tree : And my settings.py file : import io import os import environ import google.auth from google.cloud import secretmanager as sm # Import the original settings from each template from .basesettings import * try: from .local import * except ImportError: pass # Pull django-environ settings file, stored in Secret Manager SETTINGS_NAME = "application_settings" _, project = google.auth.default() client = sm.SecretManagerServiceClient() name = f"projects/{project}/secrets/{SETTINGS_NAME}/versions/latest" payload = client.access_secret_version(name=name).payload.data.decode("UTF-8") env = environ.Env() env.read_env(io.StringIO(payload)) # Setting this value from django-environ SECRET_KEY = env("SECRET_KEY") # Allow all hosts to access Django site ALLOWED_HOSTS = ["*"] # Default false. True allows default landing pages to be visible DEBUG = env("DEBUG") # Set this value from django-environ DATABASES = {"default": env.db()} INSTALLED_APPS += ["storages"] # for django-storages if "app" not in INSTALLED_APPS: INSTALLED_APPS += ["app"] # for custom data migration # Define static storage via django-storages[google] GS_BUCKET_NAME = env("GS_BUCKET_NAME") STATICFILES_DIRS = [] DEFAULT_FILE_STORAGE = … -
How to include an attribute of a foreign key in the Django Admin 'Add' page?
I have two following models: models.py: class Coordinates(models.Model): lat = models.DecimalField(max_digits=7, decimal_places=5, null=True) lng = models.DecimalField(max_digits=7, decimal_places=5, null=True) def __str__(self): return f"(lat: {self.lat}, lng:{self.lng})" class Event(models.Model): //other attributes note = models.CharField(max_length=100, blank=True) coordinates = models.ForeignKey(Coordinates, on_delete=models.CASCADE, related_name="event_coordinates") def __str__(self): return f"{self.type} by {self.creator}. {self.number_of_people}/{self.people_needed}." admin.py: from django.contrib import admin from .models import * admin.site.register(User) admin.site.register(Event) What I need to do to show 'lat' and 'lng' fields from cooridinates inside Admin Add page? -
Change _id from ObjectId to normal unique auto increment integer
I am pretty new to Django and web development so all of this is new to me as I am learning. I recently had a Django site setup and working with Postgresql. When I created it, I over complicated things and needed to use Postgresql specifcally because of one of the fields it had that SQLite did not have. Anyways, I am going to redo it (v2) and want to convert to a MongoDB. Right now I have everything set up but I noticed when I create new items from my models in the admin panel, it gets _id:ObjectId("61ba69238db76b91b4bf42f1") in the database. I am guessing this is the primary key? However, Django from my understanding is looking for a normal integer value. So when I am trying to remove things or modify things it gives me the error: Field 'id' expected a number but got 'None'. Should I be creating my own "id" field for each model? Should/can the default _id field be used? Thank you! -
QuerySet doesn't filter by user
So my code is written in Django backend and React frontend. For some reason, objects (in this case rats) aren't being filtered by the owner/user. I don't want to make permissions - anyone should be able to access someone else's rat, but in this specific list the user should only see the rats that belong to them. Running other filters work, such as birthday. But when I try filtering by user, no rats show up. There's also no error. What could be wrong? Object Serializer: class RatSerializer(FlexFieldsModelSerializer): user = serializers.CharField() body_colour = BodyColourSerializer() eye_colour = EyeColourSerializer() image = ImageSerializer() class Meta: model = rat Views: class ratViewset(FlexFieldsMixin): serializer_class = RatSerializer def get_queryset(self): userid = self.request.id return rat.objects.filter(user = userid) User serializer: class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = User fields = ('id', 'username', 'password') And the JSON output for a user: { "id": 13, "username": "new" } In the JSON output for the object/rat, it clearly says which user it belongs to. So why won't the filter work? -
HMAC-SHA-256 signature verification failure on Telegram Web Login
I'm trying to add Telegram Web Login to my Django+Vue project. I'm handling login on Vue and directly passing the authorization data taken from TG to Django via DRF. That's working fine. The problem occurs in the verification on REST's POST view. When i was using js-sha256 library on Vue it works perfectly and im getting the true value of hash string provided by sha256.hmac() function from the js-sha256 library. I'm struggling to get same hash on Python. Here is the TG data verification explained and the code i'm using in POST view: class TelegramLoginSerializer(serializers.Serializer): raw_data = serializers.JSONField(required=True) def create(self, validated_data): raw_data = validated_data['raw_data'] tg_data = "\n".join([f'{k}={raw_data[k]}' for k in sorted(raw_data)]) if raw_data['hash'] != self.verify_telegram_data(tg_data): return PermissionDenied() else: ... @staticmethod def verify_telegram_data(data): secret_key = hashlib.sha256(settings.TG_BOT_TOKEN.encode('utf-8')) message = data.encode('utf-8') return hmac.new(secret_key.digest(), message, hashlib.sha256).hexdigest() -
Pagination with Django Class Based View on second page is messed up with formatting
I am trying to paginate the blog created in django using class based view, the first page is ok and well formatted but next pages won't retain the formatting and "div" "container" class overrides. this is the view.py: class HomeView(ListView): model = Post template_name = 'blog.html' paginate_by = 2 The template: <div class="container"> <h1 class="" style="margin-top: 4%;">The Blog</h1> {% for post in object_list %} <div class="row d-flex justify-content-center mb-5" style="margin-top: 5%;"> <div class="row "> <div class="col" style="margin-right: 0%; padding-right: 0%; padding-left: 0%;"> <img src = '{{ post.header_image.url }}' height="250" width="100%"> </div> <div class="row text-center"> <p class="title-two" style="padding-top: 15%;">{{ post.title }} </p> </div> </div> </div> <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <li><a href="?page=1">&laquo; first</a></li> <li><a href="?page={{ page_obj.previous_page_number }}">previous</a></li> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} </span> {% if page_obj.has_next %} <li><a href="?page={{ page_obj.next_page_number }}">next</a></li> <li><a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a></li> {% endif %} </span> </div> As shown in the pictures the first page works fine but next pages mess up with formatting. -
Trying to speed up a Serializer for a Django model - too many queries made
I'm trying to speed up my API. I need to (at least I assume I need to) use SerializerMethodField to calculate different bits of info I need included with the object. When I do that, in those methods I have to get the related _set data - which ends up hitting the database. As you can imagine, once I have a list of a large amount of users (for example: when I show all users in the web API) it takes forever to return, because of those hits to the DB. I'm not sure the best way to handle this - I believe prefetch_related and/or select_related is the answer, I'm just unsure of the best way to implement those functions. My code looks like this (pastebin version): # MODELS class User(models.Model): name = models.CharField(max_length=50) # ...etc... class Assignment(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT ) job = models.ForeignKey(Job, on_delete=models.PROTECT) location = models.ForeignKey(Location, on_delete=models.PROTECT) # SERIALIZER class UserSerializer(serializers.HyperlinkedModelSerializer): assignment_job = serializers.SerializerMethodField() multiple_locations = serializers.SerializerMethodField() multiple_jobs = serializers.SerializerMethodField() class Meta: model = User fields = [ "url", "id", "username", "first_name", "last_name", "full_name", "email", "is_staff", "assignment_job", "multiple_locations", "multiple_jobs", ] def get_assignment_job(self, obj): assignment = obj.assignment_set.get(primary=True) return assignment.job.description def get_multiple_locations(self, obj): location_count = obj.assignment_set.filter( end_date__isnull=True … -
Django CreateView doesn't save object and doesn't give error
I'm working on a new project and I'm having difficulties adding new objects from the users page. It can be added from admin dashboard. This is the model: class Product(models.Model): title = models.CharField(max_length=150) price = models.IntegerField() image = models.ImageField(upload_to='products') description = models.TextField(max_length=500) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('product-details', kwargs={'pk': self.pk}) I have this view: class ProductCreateView(LoginRequiredMixin, CreateView): model = Product fields = ['title', 'image', 'description', 'price'] def form_valid(self, form): form.instance.owner = self.request.user #form.save() return super().form_valid(form) product_form.html: {% extends "index/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Product</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Save</button> </div> </form> </div> {% endblock content%} I tried a couple of times and I didn't work. So I searched for solutions and tried the following: instance = form.save(commit=False) instance.owner = self.request.user instance.save() return super().form_valid(instance) and this self.object.owner = self.request.user self.object = form.save() return super(ProductCreateView, self).form_valid(form) within the form_valid(). Neither of them worked. So I can open the form and fill the fields. When I send it, the object is not saved but it doesn't give any error. It just reloads the form. -
Is it possible read the document.body of a secondary window of different domain with postMessage()?
I am bulding a web app: a SPA using React in frontend and Django rest framework to API endpoints. I am in the part of the social login, which is done entirely in the backend (there is a exchange of providers tokens by own JWTs), so it is necessary make the request to the server, which redirect the user to the login of the specific provider. However, due to Facebook, Google and others providers do not permit this request using AJAX, I decided to create a popup (through window.open()) to make this redirection. Whether login is successful this window is redirect again towards a View of Django that returns a JSON with the JWT. Hence, this secondary window has a JWT in the domain of my server (Django). I planned read this JSON from the body of this secondary window to get the JWT, and I read (Code response form parent window, SecurityError: Blocked... and others) the only way to communicate windows in different domains is with postMessage(). But when I try, I receive the next message: SecurityError: Permission denied to access property "document" on cross-origin object In fact both of them are runnning in localhost, just with different port. … -
Django: What is wrong with this simple code to make user session validation. No errors in Visual Studio Code. Code in body section not work properly
I'm new here. Before asking the question, I tried to search. I have become convinced that it should work, and it is not. It works: <a href= "{% url 'logout' %}" class="btn btn-danger btn-sm">Logout</a> <a href= "{% url 'login' %}" class="btn btn-success btn-sm">Login</a> It is not: {% if user.is_autenticated %} <p>Hello {{ user.username }}</p> <a href= "{% url 'logout' %}" class="btn btn-danger btn-sm">Logout</a> {% else %} <a href= "{% url 'login' %}" class="btn btn-success btn-sm">Login</a> {% endif %} I am a beginner, so sorry experienced colleagues. :) Does anyone have an idea why? In the browser, you can always see only the login button, even after logging in. The login procedure works correctly because without logging in you cannot manipulate the data. Br Marek -
Django - querying and comparing multiple many to many relationships
Case: a user is creating a new requisition. I need to filter the fields(clearances) he is allowed to select/see in his requisition; based on a comparison of the following: users department(s) users workplace(s) compared against departments workplace(s) departments clearance fields clearance workplace(s) my models: class Place(models.Model): ... name = CICharField(max_length=100) descr = models.TextField(null=True, blank=True) parent = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True,blank=True, related_name='children', ) #------------------------------ class User(AbstractUser): .... place = models.ManyToManyField(Place, blank=True, related_name='users') organization = models.ManyToManyField(Organization, blank=True) .... #------------------------------ class Organization(models.Model): ... parent = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True,blank=True, related_name='children', ) place = models.ManyToManyField(Place, blank=True) ... #------------------------------ class Clearance(models.Model): ... parent = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='clearances') place = models.ManyToManyField('Place', blank=True, related_name='clearances') name = models.CharField(max_length=200) ... #------------------------------ class Requisition(models.Model): ... created_by = models.ForeignKey(User, on_delete=models.CASCADE) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) place = models.ManyToManyField(Place, blank=False, related_name='requisitions') clearance = models.ManyToManyField(Clearance, blank=True, related_name='requisitions') ... Example scenario: user is a member of only 1 department: "Tech dpt" user is located in "London" and "Edinburgh" Tech dpt is located in "London", "Edinburgh" and "Glasgow" The clearances for "Tech dpt" is C1: London C2: Glasgow C3: London and Edinburgh C4: Edinburgh C5: London, Edinburgh and Glasgow the closest query I manage is the following: users_clearances = ( Clearance.objects #fetch all clearances attached to … -
How can I limit choices in this model form's ModelChoice widget using attributes in itself?
I can't find the way to limit the widget's choices to the objects in the fields 'jugadorA', and 'jugadorB', which are Jugador models. the form in forms.py: class ganadorForm(ModelForm): class Meta: model = Juego fields = ['ganador', 'jugadorA', 'jugadorB', 'torneo', 'ronda'] widgets = { 'ganador': ModelChoiceField(queryset=queryset=Jugador.objects.filter(Q(fields['jugadorA']) | Q(fields['jugadorB'])), to_field_name='nombre') } the model in models.py class Juego(models.Model): torneo = models.ForeignKey(Torneo, on_delete=models.CASCADE, null=False) ronda = models.ForeignKey(Ronda, on_delete=models.CASCADE, null=False) jugadorA = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, related_name='jugadorA') jugadorB = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, related_name='jugadorB') ganador = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, default=None, related_name='ganador') -
different classes for the same field rendered manually, each class is seen by different html files
Hello I have a question and it is that I want to place a class here {{form.status}} The problem is that {{form.status}} I am using it in a file called list.html and another called add.html. I already put the class from forms.py with widgets and I am using it in add.html file. I need another class for {{form.status}} that is only seen by the list.html file <div class="mb-3"> <label class="form-label mb-4" for="validationCustom14">Status</label> {{ form.status }} </div> -
Django models.foreignKey not being picked up and causing a Not Null Constraint error
Fairly new to Python and Django and having an issue with a foreignKey in that it's not being picked up. I am loading the data from some JSON I've get from an API call. There are two models I'm looking at, Team and Player. models (snipped for brevity): class Team(models.Model): code = models.IntegerField(null=True) name = models.CharField(max_length=30, null=True) short_name = models.CharField(max_length=3, null=True) id = models.IntegerField(primary_key=True) class Player(models.Model): total_points = models.IntegerField(null=True) squad_number = models.IntegerField(null=True) id = models.IntegerField(primary_key=True) goals_scored = models.IntegerField(null=True) minutes = models.IntegerField(null=True) team = models.IntegerField(null=True) team_code = models.IntegerField(null=True) player_team = models.ForeignKey(Team, on_delete=CASCADE) Both models have a unique id, id and code. Strange, but that's the way the data comes! Team.code maps to Player.team_code and Team.id maps to Player.team. In reality I could use either. I created player_team in Player with a ForeignKey link back to Team. I load and save Team first, then Player. teams = [Team(**data_dict) for data_dict in data['teams']] Team.objects.all().delete() Team.objects.bulk_create(teams) players = [Player(**data_dict) for data_dict in data['elements']] Player.objects.all().delete() Player.objects.bulk_create(players) The error I get is django.db.utils.IntegrityError: NOT NULL constraint failed: players_player.player_team_id I don't really understand how exactly it is linking the two models. I can see that in Player it is saying models.ForeignKey(Team...) so that makes sense. But how … -
Where can I find django(ORM) practice problems?
I'm really finding it very difficult to source practice problems for Django and its ORMs. I've heard Mosh's paid course has such exercises. I'm just getting started with Django mostly referring to youtube and its official documentation. I hope one of you who reads this could help me out. I don't know if this is the right forum to ask. Thanks in advance! -
Add CSRF to locust post request to prevent django error - Forbidden (CSRF cookie not set.)
How to add CSRF to the URL to test django from locust to prevent the error Forbidden (CSRF cookie not set.)? Here is what I have tried: @task def some_task(self): response = self.client.get("/") csrftoken = response.cookies['csrftoken'] self.client.post( "api/", {'csrfmiddlewaretoken': csrftoken}, headers={ 'X-CSRFToken': csrftoken, }) -
Is there any way to make this filter query smaller
These are my tables: class Employee(models.Model): name = models.CharField() class Job(models.Model): title = models.CharField() class Employee_Job(models.Model): employee_f = models.ForeignKey(Employee, on_delete=models.CASCADE) job_f = models.ForeignKey(Job, on_delete=models.CASCADE) class Salary(models.Model): employee_job_f = models.ForeignKey(Employee_Job, on_delete=models.CASCADE) @property def name(self): return Employee.objects.filter(id = ( Employee_Job.objects.filter(id = self.employee_job_f_id ).first().employee_f )).first().name This query seems very long to me, I thought select_related() should help with this, but it follows foreign keys and return ALL results not the result that is related to THIS instance of Salary. -
How can I add Django table list on edit page change_form.html?
Friends, how can I add into admin edit page Django admin like table? So, I got MaterialAdmin. I've added change_view() function in it and all the necessary data put into extra_content like this: class MaterialAdmin(admin.ModelAdmin): change_form_template = 'admin/change_material_form.html' search_fields = ['name'] autocomplete_fields = ("manufacturer", ) list_display = ("_show_name_with_manufacturer", "_show_material_groups_quantity", "_show_boxing", "unit",) def get_queryset(self, request): qs = super().get_queryset(request) return qs.select_related("manufacturer").prefetch_related("material_group", "material_item", "unit") def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} material = Material.objects.filter(id=object_id).select_related("manufacturer").prefetch_related("material_group", "material_item", "unit").first() material_items = material.material_item.all() material_groups = material.material_group.all() works = MaterialGroupWork.objects.filter(material_group__in=material_groups).distinct() extra_context['material_items'] = material_items extra_context['material_groups'] = material_groups extra_context['works'] = works return super(MaterialAdmin, self).change_view( request, object_id, form_url, extra_context=extra_context, ) admin.site.register(Material, MaterialAdmin) Now I have access to the data in my custom change_material_form.html .... <div> {% for material_item in material_items %} {{ material_item }} {% endfor %} </div> <div> {% for material_group in material_groups %} {{ material_group }} {% endfor %} </div> <div> {% for work in works %} {{ work.work }} {% endfor %} </div> What I really want is to replace those divs with Django Admin tables. How can I implement this? I looked in the template file "change_list_results.html" and it has some result_headers и results data. But I don't know how to get "results" … -
Django Template Not Receiving Context Object
I'm trying to implement a simple sign up form and slightly tearing my hair out. For some reason, the view doesn't seem to be properly passing the context object I pass it (regardless of what it is.) here's my code: urls.py path(r"signup/", client_views.signup_view, name="page-signup") views.py def signup_view(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('page-index') else: form = SignUpForm() context = {'form': form} return render(request, 'registration/signup.html', context=context) registration/signup.html {% extends "base.html" %} {% load static %} {% block header %} Sign Up {% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign Up</button> </form> {% endblock %} forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password1', 'password2', ) I've confirmed it's generating the form properly as html it's also definitely rendering the correct template doesn't pass any context even if it's just a string or something doesn't work with any forms doesn't work in other templates, implying to me it's in the view … -
See variable values in developer tools for Django templates
I have a template in Django which uses some variables. For example, I use {% with swatch_matrix=item_group.get_swatch_matrix %} Without rendering this on-screen is there a way to use the developer tools, or something else, to check what value is being generated here? -
Python Django - dynamically add and create objects in ModelMultipleChoiceField
I have a problem with something that I thought was quite common, but I cannot find the answer to it anywhere. I have 2 models Item and Group, where an item can be a member of many (or none) groups. I am writing a view for creating an Item. My code looks like this: # models.py class Group(models.Model): ... class Item(models.Model): item = models.CharField(...) groups = models.ManyToManyField(Group) # forms.py class NewItemForm(forms.Form): item = forms.CharField() groups = forms.ModelMultipleChoiceField( queryset = models.Group.objects.all(), widget = forms.CheckboxSelectMultiple, required = False ) In my template I add javascript that allows user to dynamically crate a new checkbox (and setting it's value to something like __new__group_name) for a new group. What I want to accomplish it to allow user to create a new group and add an item to it, while this item is currently being created. Unfortunately this cannot work, because checkboxes generated by Django are sending a primary key of Group and there obviously is not a group with primary key __new__group_name so validation of this form failes. While it is correct and I am glad it does, I cannot find a easy solution for this problem. The only thing I can think about … -
django: repeat testcase with different fixtures
I have a Django TestCase, all of whose tests I'd like to run for two different sets of data (in this case, the Bike object whose colour can be red or blue). Whether that's through loading different fixtures, or the same fixtures and manipulating the colour, I have no preference. See below example: class TestBike(TestCase): fixtures = [ "testfiles/data/blue_bike.json", ] def setUp(self, *args, **kwargs): self.bike = Bike.objects.get(color="blue") run_expensive_commands(self.bike) def test_bike_1(self): # one of many tests def test_bike_2(self): # second of many tests One way I considered was using the parameterized package, but then I'd have to parameterize each test, and call a prepare() function from each test. Sounds like a whole lot of redundancy. Another is to multiple-inherit the test with different fixtures. Also a bit too verbose for my liking. -
how i can connect between 2 django services using mqtt?
"how i can connect two Django services using MQTT (i want to create a customer in the first service and then dispatched it to the another service)` -
Speeding up Django Rest Framework Model Serializer N+1 Query problem
I have a DRF ModelSerializer class that serializes anOrder model. This serializer has a field: num_modelA = serializers.SerializerMethodField() ` def get_num_modelA(self, o): r = ModelA.objects.filter(modelB__modelC__order=o).count() return r Where ModelA has a ForeignKey field modelB, ModelB has a ForeignKey field modelC, and ModelC has a ForeignKey field order. The problem with this is obviously that for each order that gets serialized it makes an additional query to the DB which slows performance down. I've implemented a static method setup_eager_loading as described here that fixed the N+1 query problem for other fields I was having. @staticmethod def setup_eager_loading(queryset): # select_related for "to-one" relationships queryset = queryset.select_related('modelD','modelE') return queryset My idea was I could use prefetch_related as well to reduce the number of queries. But I am unsure how to do this since Order and ModelA are separated by multiple foreign keys. Let me know if any other information would be useful