Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run celery task everyday at 3:00 am in every timezone? Django
I need to run a task a 3:00 am everyday for multiple timezones, in the app every organization has a timezone. class Organization(models.Model): timezone = models.IntegerField(choices=((i, i) for i in range(-12, 13))) So if two organizations has different timezones the task should be executed a 3:00 am in their respective timezones i.e. not at the same time. How can I accomplish that? -
how to add new entered input value to table django ajax
i'm trying to add a new entered value to a table after success method runs using ajax , i've used ModelForm . i want to add the new entry to the table body row ! , i've tried alot , but still i cant figure it out ! i most appreciate your helps class MainGroup(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) date = models.DateTimeField(auto_now_add=True) my views.py @login_required def create_maingroup(request): lists = MainGroup.objects.all().order_by('-pk') form = MainGroupForm() if request.is_ajax() and request.method == 'POST': form = MainGroupForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.admin = request.user obj.save() return JsonResponse({'success':'success'}) else: return JsonResponse({'sucess':False,'error_msg':form.errors,'error_code':'invalid'}) context = { 'form':form,'lists':lists } return render(request,'products/create_maingroup.html',context) const form = document.getElementById('main_form') form.addEventListener("submit",submitHandler); function submitHandler(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url 'products:create-maingroup' %}', data : $('#main_form').serialize(), dataType: 'json', success: successFunction, }); } function successFunction(data) { console.log(data.success=='success') if (data.success=='success') { form.reset(); obj = $('#main_form').serialize(); //i have to append new entred values here //but i dont know how to get inputs and set the admin //name who created the post ! alertify.success("added") } else if(data.error_code=='invalid'){ for(var key in data.error_msg){ if(key == 'main_type'){ document.getElementById('main_error').removeAttribute('hidden') document.getElementById('main_error').innerHTML = data.error_msg[key][0] } } } } my html page <div class="col-md-12"> <div class="card card-info"> <div class="card-header"> <div class="card-tools"> <button … -
Django Spam URL blocker form entering into my application
I have a Django application that is working fine. Now after some time, I come across some spam URLs that are getting processed by my application. Is there any way I can block these particular URLs from entering into my application. I don't what these URLs to even reach my urls.py? Thanks in advance -
Django test api code : Got an error creating the test database: database "test_postgres" already exists
I made test code for my APIs(Django web framework). It ran with no errors about 3 hours ago(It is not first time running test codes(more than 1k times)) How should I debug?? Im using macOS. directory is my_project/order_api/tests/test_order1.py I ran the code by clicking arrow in test_order1.py file. This is DATABASE setting DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.postgresql"), "NAME": os.environ.get("SQL_DATABASE", "postgres"), "USER": os.environ["SQL_USER"], "PASSWORD": os.environ["SQL_PASSWORD"], "HOST": os.environ["SQL_HOST"], "PORT": os.environ["SQL_PORT"], }, } This is Error Message Creating test database for alias 'default'... Got an error creating the test database: database "test_postgres" already exists Type 'yes' if you would like to try deleting the test database 'test_postgres', or 'no' to cancel: yes Destroying old test database for alias 'default'... Got an error recreating the test database: database "test_postgres" is being accessed by other users DETAIL: There is 1 other session using the database. -
How do i save the info typed and display in another page in html, django
How do i save the info typed in a form and display in the following page which tells me what are the details I type and ssaved in the library -
TemplateDoesNotExsist in Django 3.2.5
I am a 13 year old programmer, new to Django trying to add 2 numbers. But as soon as I give the input it spits out an error. The following are all the details to my project. -
Increase Django logs query time precision
I am currently using the Django shell in debugging mode in order to benchmark my queries. This is an example of what I get: >>> Item.objects.filter(param1=63) (0.001) SELECT `items`.`id`, `items`.`param1`, `items`.`param2`, FROM `items` WHERE `items`.`param1` = 63; args=(63,) Most of the results I am getting lay in the order of a millisecond, so I was wondering: is it possible to increase the query precision say, one or two orders of magnitude in order to tell them apart? I am using MariaDB as a database. mariadb --version mariadb Ver 15.1 Distrib 10.4.11-MariaDB, for Linux (x86_64) using readline 5.1 Thank you in advance. Regards. -
Path does not exist or is inaccessible error when using opencensus-python
I'm getting the following errors when I try to integrate opencensus-python in my dockerized Django project. ERROR: Path /tmp/opencensus-python-<hash-code>/2021-07-26T070705.948749-147e2037.blob@2021-07-26T070828.122386.lock does not exist or is inaccessible. ERROR: Path /tmp/opencensus-python-<hash-code>/2021-07-26T085046.693213-b80f5ca1.blob.tmp does not exist or is inaccessible. I did a bit of searching and found that this error is returned in _check_storage_size but what does it mean and how do I fix it? -
AttributeError: 'CustomUser' object has no attribute 'items' - Unit Test Phase
I am working on a book project. For this project, I have been already created a custom user model and using it. However, today I tried to test this model. When I want to run this code, it returns "AttributeError: 'CustomUser' object has no attribute 'items'" response. I don't understand where am I doing wrong. If I send the data in dictionary type, the test works, but if I want to send in instance type, it returns the error. Custom User Model class CustomUser(AbstractUser): GENDER_CHOICES = ( (1, AccountStrings.CustomUserStrings.gender_choice_male), (2, AccountStrings.CustomUserStrings.gender_choice_female), (3, AccountStrings.CustomUserStrings.gender_choice_other), ) USER_TYPE_CHOICES = ( (1, AccountStrings.CustomUserStrings.user_type_choice_default), (2, AccountStrings.CustomUserStrings.user_type_choice_child), (3, AccountStrings.CustomUserStrings.user_type_choice_parent), (4, AccountStrings.CustomUserStrings.user_type_choice_instructor), ) objects = CustomUserManager() email = models.EmailField(max_length=255, unique=True, null=False, blank=False) identity_number = models.CharField( max_length=11, unique=True, verbose_name=AccountStrings.CustomUserStrings. identity_number_verbose_name) birth_date = models.DateField( null=True, blank=True, verbose_name=AccountStrings.CustomUserStrings.birth_date_verbose_name) gender = models.PositiveSmallIntegerField( choices=GENDER_CHOICES, default=1, verbose_name=AccountStrings.CustomUserStrings.gender_verbose_name) user_type = models.PositiveSmallIntegerField( choices=USER_TYPE_CHOICES, default=1, verbose_name=AccountStrings.CustomUserStrings.user_type_verbose_name) class Meta: verbose_name = AccountStrings.CustomUserStrings.meta_verbose_name verbose_name_plural = AccountStrings.CustomUserStrings.meta_verbose_name_plural def __str__(self): return f"{self.first_name} {self.last_name}" Unit Test from rest_framework.test import APITestCase from django.urls import reverse from django.contrib.auth import get_user_model User = get_user_model() class CustomUserRegistrationTests(APITestCase): url = reverse("account:register") def setUp(self) -> None: self.user1 = User.objects.create_user(first_name="John", last_name="Doe", email="johndoe@example.com", username="demo", password="Pas12wor21d", identity_number = "12345678910", user_type = "2", gender = 1) def test_user_instance(self): """ Check the … -
Braintree Client token generate method throws an XML error inside Django
I am using the below code to generate Client Token from the braintree gateway inside my payment View in Django. def generate_token(request,id,token): if not validate_user_session(id,token): return JsonResponse({"error":"Invalid session"}) gateway = braintree.BraintreeGateway( braintree.Configuration( braintree.Environment.Sandbox, merchant_id="xxxxxxxxxx", public_key="xxxxxxxxxxxx", private_key="xxxxxxxxxxxxxxxxxxxxxx" ) print(gateway.client_token.generate()) return JsonResponse({"clientToken":gateway.client_token.generate(), "success":True}) This throws an error xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 0 However, the code works fine outside Django and in Python Shell and generates the token successfully. I don't seem to understand what is the issue ? The Ids and tokens are same in both the cases. Any help is appreciated. -
FileNotFoundError: [Errno 2] No such file or directory | FileNotFoundError: [WinError 2] The system cannot find the file specified:
I am trying to Upload Files using Django templates, But on save_project I get this traceback error FileNotFoundError: [WinError 2] The system cannot find the file specified: 'E:\\forefront-v1.0\\media\\uploads\\temp\\10\\Video%20Sensor%20-%2013370_1798858.mp4' -> 'E:\\forefront-v1.0\\media/uploads/project-videos/Video%20Sensor%20-%2013370_1798858.mp4' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\forefront-v1.0\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\forefront-v1.0\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\forefront-v1.0\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\forefront-v1.0\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "E:\forefront-v1.0\venv\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "E:\forefront-v1.0\venv\lib\site-packages\django\contrib\auth\mixins.py", line 109, in dispatch return super().dispatch(request, *args, **kwargs) File "E:\forefront-v1.0\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "E:\forefront-v1.0\projects\views.py", line 2660, in post project_id = self.save_project( File "E:\forefront-v1.0\projects\views.py", line 2792, in save_project video1 = self.upload_video_locally(video1) if video1 else None File "E:\forefront-v1.0\projects\views.py", line 2872, in upload_video_locally shutil.move(temp_file_path, saved_file_path) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 826, in move copy_function(src, real_dst) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 435, in copy2 copyfile(src, dst, follow_symlinks=follow_symlinks) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 264, in copyfile with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst: FileNotFoundError: [Errno 2] No such file or directory: 'E:\\forefront-v1.0\\media\\uploads\\temp\\10\\Video%20Sensor%20-%2013370_1798858.mp4' [26/Jul/2021 13:12:27] "POST /upload/ HTTP/1.1" 500 23208 In project settings.py # Upload MEDIA_URL = '/media/' … -
how to get update url in django - ajax
i'm trying to update and delete post with ajax , class MainGroup(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) date = models.DateTimeField(auto_now_add=True) views.py def list_maingroup(request): lists = MainGroup.objects.all().order_by('-pk') data = [] for obj in lists: item = { 'id':obj.id, 'admin':obj.admin.username, 'main_type':obj.main_type, 'date':obj.date } data.append(item) return JsonResponse({'data':data}) @login_required def create_maingroup(request): form = MainGroupForm() if request.is_ajax() and request.method == 'POST': form = MainGroupForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.admin = request.user obj.save() return JsonResponse({'success':'success'}) else: return JsonResponse({'sucess':False,'error_msg':form.errors,'error_code':'invalid'}) context = { 'form':form } return render(request,'products/create_maingroup.html',context) my update views.py @login_required def update_maingroup(request,id): object = get_object_or_404(MainGroup,id=id) form = MainGroupForm(instance=object) if request.method == 'POST': form = MainGroupForm(request.POST,instance=object) if form.is_valid(): form.save(commit=True) return JsonResponse({'success':'success'}) else: return JsonResponse({'sucess':False,'error_msg':form.errors,'error_code':'invalid'}) context = { 'form':form } return render(request,'products/update_maingroup.html',context) my urls.py app_name = 'products' urlpatterns = [ path('',create_maingroup,name='maingroup'), path('maingroup/update/<int:id>/',update_maingroup,name='update_maingroup'), path('maingroup/delete/<int:id>/',delete_maingroup,name='delete_maingroup'), const form = document.getElementById('main_form') form.addEventListener("submit",submitHandler); function submitHandler(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url 'products:maingroup' %}', data : $('#main_form').serialize(), dataType: 'json', success: successFunction, }); } function successFunction(data) { if (data.success) { form.reset(); alertify.success("added") } else if(data.error_code=='invalid'){ for(var key in data.error_msg){ if(key == 'main_type'){ document.getElementById('main_error').removeAttribute('hidden') document.getElementById('main_error').innerHTML = data.error_msg[key][0] } } } } $.ajax({ type:'GET', url:'{% url 'products:list-maingroup' %}', success:function(response){ console.log(response) data = response.data var k = '<tbody>' for(i = 0;i < data.length; i++){ k+= … -
Djngo - How can I change profile view in admin's panel?
Well, I created a model Profile: class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, ) website = models.URLField(blank=True) bio = models.CharField(max_length=240, blank=True) And added it to admin.py: @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): model = Profile So, I have user's panel on mu admin's panel. But every profile in the list of profiles are called 'profile object(1)', 'profile object(2)' and etc, but when I tap on the link, I can see the user's name. So, how can I can change the view of profiles in the list of profiles so they are called there as user is called? How it looks like in admin's panel How it looks like inside the profile -
Django user registration without username
I am making django registration form At first this code works well class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username","email", "password1", "password2"] def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/login") However now I want to make email as username, so my idea is like this class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["email", "password1", "password2"] #delete username from home. def register(response): if response.method == "POST": if not response.POST._mutable: response.POST._mutable = True response.POST['username'] = random.randrange(1000000) # force change username form = RegisterForm(response.POST) if form.is_valid(): form.save() However after this username is not registered. What is wrong?? -
User customizable Template
So I have a template to render a PDF and I want to be able to customize this PDF. But in this text some dynamic information is added so I want to do the following thing: In a model.TextField I want to set a string like string = 'Text {{ count }} Text text' and than I want to render this string in my template like so: <p> {{ string }} </p> How can I get this so that the template engine renders it like this: <p> Text {{ count }} Text text </p> -
upload file from django s3 backend to ftp server using paramiko ssh client
i am working django application. i need to share the file from django s3 storage to a ftp server. i am generating a file and store django filefielda and share the file from filefield to ftp server. i am using paramiko sshclient. I am using the code below which shows the error This backend doesn't support absolute paths. code: ftp_client.put(file, remote_file_path) -
Django - Migrate a model field from float to an array of float
I have a postgres databse in a Django application. We designed a database and started to populate it on production. However it appears that one of the field on one of our model is supposed to be an Array of float instead of a float. To do so I'd like to use the ArrayField from postgres. But if I juste replace my models.FloatField(verbose_name=_('Space between nozzles')) by models.ArrayField(models.FloatField(verbose_name=_('Space between nozzles'))) I got this error when I try to migrate: cannot cast type double precision to double precision[] Can I convert my model field type this easily ? Thanks -
Posting to multiply related tables Django
I would like to create my own endpoint for POST request to two related tables. I have two tables User and Userattribute. models.py class User(models.Model): email = models.CharField(unique=True, max_length=180) roles = models.JSONField(default=dict) password = models.CharField(max_length=255, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) firebase_id = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(default=now) progress_sub_step = models.IntegerField(blank=True, null=True) step_available_date = models.DateTimeField(blank=True, null=True) progress_step = models.IntegerField(blank=True, null=True) active = models.IntegerField(default=1) last_login_at = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'user' class Userattribute(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name = 'attribute') attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) The table Userattribute contains the field user which is OnetoOne to Id primary key from User table. I tried to implement POST to two tables in serializers.py In the commented section there is a create definition which works perfectly for me. However, I wouldlike to move it to views.py as register_in_course endpoint serializers.py class FilmSerializer(serializers.ModelSerializer): class Meta: model = Film fields = ['tytul', 'opis', 'po_premierze'] class UserattributeSerializer(serializers.ModelSerializer): class Meta: model = Userattribute fields = ['user', 'attribute'] class UASerializer(serializers.ModelSerializer): class Meta: model = Userattribute fields = ['attribute'] class UserSerializer(serializers.ModelSerializer): attribute = UASerializer(many = False) class Meta: model = User fields = ['email', 'name', 'firebase_id', 'attribute'] # This is what workks … -
Django how to know which button is clicked in case I have many buttons?
For an online shopping website, I have many products where each product contains an add to cart button, I want to know which button was clicked to know which product is related to that button. I am new at Django and frontend so I think it is common but I don't know what does that and should it be javascript? <div class="row"> {% for product in products %} <div class="col-lg-4"> <img alt="" class="thumbnail" src="{{ product.images.all.0.image.url }}"> <div class="box-element product"> <h5><strong>{{ product.name }}</strong></h5> <hr> <button class="btn btn-outline-secondary add-btn"> Add to cart</button> <a class="btn btn-outline-success" href="{% url 'detail' %}"> View</a> <h4 style=" float: right"><strong>{{ product.price }}</strong></h4> </div> </div> {% endfor %} </div> -
Django Development Server is not accessible from other computer : This Site Cannot be Reached
I am trying to access my django dashboard from other computer over the same network through LAN. I have updated the setting.py with following lines to access from other computers: DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost','myip'] I have also Updated ALLOWED_HOSTS = ['*'] but when i run the server from the any of following command in CMD as well as in the terminal of VSCODE : python manage.py runserver 0.0.0.0:8000 python manage.py runserver myip:8000 it says This Site cannot be reached myip took too long to respond. I am able to access my dashboard on my system and it works fine but when i access it from other computer over the same network it says This site cannot be reached. Moreover, few days ago it was accessible from other computers over the same network but now giving this following error: -
How do I add paginator to thid django code?
I have a system where users can view complaints they have registered on one page. But the problem is that only four complaints can be viewed at a time on the page. How can I add pageinator to the code so that the next four complaints can be viewed on the other page in the correct format and template: views.py: def History(request): complaint_data = Complaint.objects.filter(user=request.user) context = { 'complaint':complaint_data } return render(request, 'myHistory.html', context) template: <!-- Middle Container --> <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">My Complaints</h1> <p class="all-comp-txt">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> {%for c in complaint %} <a href="{% url 'Complaint' c.pk %}" style="color:black;"> <div class="container comp-con-{{forloop.counter0}}"> <p style="color: #D37A19; margin-left: -130px; margin-top: -5px;">Report number:</p> <p class="history-level-1">{{c.reportnumber}}</p> <p class="comp-title-1">{{c.event_type}}</p> <p class="comp-sub-1">{{c.event_text|truncatechars:85}}</p> </div> </a> {%endfor%} </div> css: enter code h.comp-con-0 { display: flex; flex-direction: column; justify-content: space-between; align-items: center; padding: 11px 8px; position: absolute; width: 300px; height: 140px; left: 160px; top: 190px; background: #FFEEDB; box-shadow: 1px 1px 2px rgb(0 0 0 / 25%); border-radius: 10px; } .comp-con-1 { display: flex; flex-direction: column; justify-content: space-between; align-items: center; padding: 10px; position: absolute; width: 300px; … -
Django social allauth with JWT token
I made registration via social networks using the allauth library. Added the necessary settings: ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = "email". and applications: "allauth", #registration "allauth.account", # registration "allauth.socialaccount", # registration "allauth.socialaccount.providers.vk", # registration via VK. and in urls.py I also wrote: url(r"^accounts/", include("allauth.urls")) The problem is that sometimes the provider after registration may not provide an email. And my users are identified using mail. Signup: I want the user to be redirected to a page with an email entry and send a confirmation link to this email after the suppliers confirm the entered data is correct. Signin: I want to return the JWT token to the user after confirming the providers that the entered data is correct How to implement a signin/signup system in Django DRF JWT with allauth library? (apparently I need to write custom views, but I tried - unsuccessfully) -
How to set url id to a specific field django
I'm looking to create a model for users to bookmark a recipe. I have the below, where a recipe value is passed through a POST request: models.py class PublishedRecipeBookmark(models.Model): recipe = models.ForeignKey( PublishedRecipe, on_delete=models.PROTECT, related_name="bookmarks" ) bookmarked_by = models.ForeignKey(User, on_delete=models.PROTECT) bookmarked_at = models.DateTimeField(auto_now_add=True) serializers.py class PublishedRecipeBookmarkSerializer(serializers.ModelSerializer): bookmarked_by = UserSerializer(read_only=True) class Meta: model = models.PublishedRecipeBookmark fields = ["recipe", "bookmarked_by", "bookmarked_at"] def create(self, validated_data): request = self.context["request"] ModelClass = self.Meta.model instance = ModelClass.objects.create( **validated_data, **{"bookmarked_by": request.user} ) return instance views.py @permission_classes([IsAuthenticated]) class PublishedRecipeBookmarkView(generics.CreateAPIView): queryset = models.PublishedRecipeBookmark.objects.all() serializer_class = PublishedRecipeBookmarkSerializer urls.py path("published-recipes/bookmarks", PublishedRecipeBookmarkView.as_view()), I want to change the url to something like this, so that the recipeid is passed through the url (int:id). urls.py path("published-recipes/bookmarks/<int:id>", PublishedRecipeBookmarkView.as_view()), How can I achieve this so that the view recognises the id as a recipeid for a PublishedRecipe (a foreign key relationship is established in the model)? -
In django how can I loop through specific fields in the parent model (user) including some specific fields in the attached child model (userprofile)
I have a table in my template, For each individual user in the User model, I want to loop through their username, phone, & email. I also want to include from the Profile model the user's age, state, & address. my model classes in models.py: class User(models.Model): ... username = models.CharField(max_length=100, null=True) phone = models.CharField(max_length=20, null=True) email = models.EmailField(max_length=100, blank=True, null=True) password = models.CharField(max_length=100, null=True) ... class Profile(models.Model): ... users = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True, related_name='userprofile') age = models.PositiveIntegerField(blank=True, null=True) state = models.CharField(max_length=20, null=True) address = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(upload_to='profile_pics/', null=True) ... my views in views.py: ... def registeredUsers(request): users = User.objects.all() context = {'users': users} return render(request, 'users.html', context) ... My template has the table contents below: ... </tbody> {% for i in users %} <tr> <td>{{ i.username }}</td> <th>{{ i.phone }}</th> <th>{{ i.email }}</th> <td>{{ i.age}}</td> <td>{{ i.state}}</td> <td>{{ i.address}}</td> </tr> {% endfor %} </tbody> ... How can I make sure that the User model pulls the fields of the Profile model with it? -
Efficient way of dividing a querySet with a filter, while keeping all data?
I have a 'Parts' model, and these parts are either linked to a 'Device' model or not yet. The actual "link" is done via more than just one ForeignKey, i.e. I have to go through 3 or 4 Models all linked between each other with ForeignKeys to finally get the data I want. My question is: What is the most efficient way of getting both the linked and non-linked parts ? Right now, I am getting all parts and simply outputting that, but I would like a little separation: allParts = Parts.object.all() I know I could do something similar to this: allParts = Parts.object.all() linkedParts = allParts.objects.filter(...device_id=id) nonLinkedParts = allParts.objects.exclude(...device_id__in=[o.id for o in linkedParts]) But is that really the most efficient solution ? I feel like there would be a better way, but I have not yet found anything in the docs about it. Just to clarify, there are only linked, and non-linked parts. These are mutually exclusive and exhaustive. Thank you very much