Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use same django app for multiple sites like example.com, company.com and subdomains?
I would like to use django sites framework to get access with different URL´s to same application but it would be interesting to use the subdomains also, i do not know if django hosts will work with the sites framework. Would you mind to clarify my doubts, I haven´t found anything clear. -
User uploads and amazon ec2 instance
Not sure if this is the right place to ask this question but I would love to get an answer to this specific question. I have a Django SaaS that requires a user to upload a 5mb-15mb file per connection. I am expecting to scale up to 100 users. Most likely the app will be used daily by users. I am using nginx and gunicorn. In this scenario, what ec2 instance make sense to use and how many server should configurate to handle the uploads? I know that tests are necessary to exactly figure it out but in general, what kind of resource are required for this type of setup? -
Django Organizations with Django REST?
I wish to create several instances of several models in a "wizard" (think https://django-formtools.readthedocs.io/en/latest/) I decided not to use django-formtools because it just gave me a headache trying to customize it. Instead, I'll try to rely on DRF to create a rest api based wizard. My concern is - how can "translate" an existing ModelForm to work with DRF? I'm using Django Organizations, and one of the modelforms is for creating an organization through the provided ModelForm: class OrganizationAddForm(forms.ModelForm): """ Form class for creating a new organization, complete with new owner, including a User instance, OrganizationUser instance, and OrganizationOwner instance. """ email = forms.EmailField(max_length=75, help_text=_("The email address for the team owner (defaults to yours)")) def __init__(self, request, *args, **kwargs): self.request = request super(OrganizationAddForm, self).__init__(*args, **kwargs) class Meta: model = Organization exclude = ('users', 'is_active') def save(self, **kwargs): """ Create the organization, then get the user, then make the owner. """ is_active = True try: user = get_user_model().objects.get(email=self.cleaned_data['email']) except get_user_model().DoesNotExist: user = invitation_backend().invite_by_email( self.cleaned_data['email'], **{'domain': get_current_site(self.request), 'organization': self.cleaned_data['name'], 'sender': self.request.user, 'created': True}) is_active = False return create_organization(user, self.cleaned_data['name'], is_active=is_active) Can I somehow just pop this into a APIView and call the form_class above in a post method? Or would I need … -
Generate chart data based on withdrawals and deposit infos with python django
I have date and amount informations about withdrawals and deposits of an employees balance. Exactly I have these models in django: class Withdraw(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) amount = models.PositiveIntegerField(default=0) date = models.DateTimeField(default=timezone.now) class Deposit(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) amount = models.PositiveIntegerField(default=0) date = models.DateTimeField(default=timezone.now) So I have an array containing all dates of withdraws and deposits, and another array with the cumulative sums, so the actual balance: eg: days = [3,7,9] balance = [40,20,60] What I want is to display the whole month's balance with a line chart. I use chart.js, where I have to add the X and Y axes exactly the values I would like to show. So to have a full month's view I should pass to chart js these data. days = [1...30] #in case of a 30 day long month balance = [ 0, 0, 40, 40, 40, 40, 20, 20, 60, ..........#until end of the month.......] Do you know a better approach for this? Are there any function in python to create the balance array with data for all days in a month? Thx! -
Unpack error after running compilemessages in django
I have a Django project, and it was working fine. after some merges from my teammates, now when I try to run the server, AFTER using these manage.py makemessages and manage.py compilemessage I get this error: magic = unpack('<I', buf[:4])[0] struct.error: unpack requires a buffer of 4 bytes Can anyone help ? -
{{form}} fields not populating in modal
I'm experiencing an odd behaviour. I'm calling a foundation modal dialog from a parent page (parent.html) via a <a> element. This dialog contains a form which. I have another modal and calling a similar form (for another model) on the same page which is working fine (and before you ask: I've made a test and took it out completely and still have the issue with this one). This is my code. Users/models.py class Profile(models.Model): first_name = models.CharField(max_length=120, null=True, blank=True) forms.py: from users.models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['first_name'] views.py: def venue_add_view(request): form_venue = VenueForm(request.POST or None) if form_venue.is_valid(): form_venue.save() context = { 'form_venue': form_venue, } return render(request, "venue-add.html", context) profile-add.html <div class="reveal" id="addProfile" data-reveal> <form id="addProfileForm" action='/profile-add/' onsubmit="mysubitfunction();" method='POST'> {% csrf_token %} <div class="grid-container"> <div class="grid-x grid-padding-x"> <h4>Add a new profile</h4> <div> {{form_profile.non_field_errors}} <p>Form should be here: </p> {{ form_profile }} </div> </div> <input class="button" type='submit' value='Save' /> </div> </form> parent.html: {% extends 'base.html' %} {% load static %} {% block content %} {% include '../profile-add.html' %} <a href="javascript:void(0)" data-open="addProfile">Add a new profile</a> {% endblock %} urls.py: from myapp.views import ( parent_view, profile_add_view) urlpatterns = [ path('parent_view/', parent_view, name='parent-view'), path('profile-add/', profile_add_view, name='profile-add') ] Now, … -
django/wagtail sendmail function not loading
it works perfectly in development environment but does not work for production. I am using apache2 as my server. The send mail functionality is called when a user fills in a feedback form , and the entry is saved into my database. contact/models.py/contactpage def send_mail(self, form): # `self` is the FormPage, `form` is the form's POST data on submit # Email addresses are parsed from the FormPage's addresses field addresses = [x.strip() for x in self.to_address.split(',')] print(addresses) # Subject can be adjusted, be sure to include the form's defined subject field submitted_date_str = date.today().strftime('%x') subject = self.subject + " - " + submitted_date_str # add date to email subject print(subject) content = [] # Add a title (not part of original method) content.append('{}: {}'.format('Form', self.title)) for field in form: # add the value of each field as a new line value = field.value() if isinstance(value, list): value = ', '.join(value) content.append('{}: {}'.format(field.label, value)) # Add a link to the form page content.append('{}: {}'.format('Submitted Via', self.full_url)) # Add the date the form was submitted content.append('{}: {}'.format('Submitted on', submitted_date_str)) # Content is joined with a new line to separate each text line content = '\n'.join(content) print(content) # wagtail.admin.mail - send_mail function is … -
Form creation for custom Inherited custom model
I'm very new to django. I'm working on simple login system. I have created a custom model named UserProfile which is inheriting User model by django. I have learnt to create forms that helps the user to change his profile details using the UserChangeFrom by django. But It allows changes to fields in the User model alone. But I want the form with my UserProfile model's fields too, So I created a form class inheriting this UserchangeForm. I don't know how to get the UserProfile object of current user,I tried getting it with the User objects primary key -1. but I don't think it will work for all the cases. form.py class EditUserProfileForm(UserChangeForm): website=forms.URLField(required=True) class Meta: model=UserProfile fields=( 'description', 'website', 'city', 'phone', ) def save(self, commit=True): user = get_object_or_404(UserProfile,pk=super(EditUserProfileForm, self).save(commit=False).pk-1) user.description=self.cleaned_data['description'] user.website=self.cleaned_data['website'] user.city=self.cleaned_data['city'] user.phone=self.cleaned_data['phone'] if commit: user.save() return user views.py def edit_profile(request): #print('primary:', request.user.pk-1) if request.method == 'POST': form = EditProfileForm(request.POST,instance=request.user) UserProfileForm= EditUserProfileForm(request.POST,instance=request.user) if form.is_valid() and UserProfileForm.is_valid(): form.save() UserProfileForm.save() return redirect(reverse('accounts:profile')) else: form = EditProfileForm(instance=request.user) UserProfileForm=EditUserProfileForm() args={'form':form,'UserProfile':UserProfileForm} return render(request,'accounts/edit-profile.html',args) -
webpack hot reload uses incorrect url
I'm using webpack's hot reload feature, along with Django. When I open the webpack dev server to http://127.0.0.1:3000/some/page/. I modify some Javascript to make the page hot reload. But the hot reload URL that gets fetched ends up being http://127.0.0.1:3000/some/page/bc6434656229f08c1681.hot-update.json http://127.0.0.1:3000/some/page/bc6434656229f08c1681.hot-update.js This is incorrect. The correct URL is always on based on http://127.0.0.1:3000/static. This is because /some/page/ is done through react-router, and is not an actual path on the server. Does webpack have an option to set the hot reload base URL? At the moment I'm just telling Django to redirect it, which works but isn't ideal. Ideally I would not want to write extra code in Django just for webpack's hot reload to work. P.S. My webpack config is: The way I integrate it with Django is through: devServer: { // For Webpack dev server. We use Django's static path since our index redirects to Django's index. publicPath: 'http://localhost:8000/static/', port: 3000, hot: true, inline: true, historyApiFallback: true, headers: { 'Access-Control-Allow-Origin': '*' }, proxy: { '/': { target: 'http://localhost:8000', // Redirect everything that we don't build to Django changeOrigin: true, }, }, }, -
Django, how to add 2 or more django custom filters
I am having difficulty adding 2 or more filters in jinga. <strong class="btn btn-block rounded-0 btn-outline-primary disabled" > {{ order.get_cart_total| add:500, floatformat:2 }} </strong> -
RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.Abstract BaseUser'>. Was __classcell__ propagated
Getting this error while trying to migrate databases after manually setting up postGREsql database for the project. Was trying to run the cloned quora project forked from github when this error cropped up. FULL ERROR DESCRIPTION:- RuntimeError: __class__ not set defining 'AbstractBaseUser' as . Was __classcell__ propagated to type.__new__? Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line utility.execute() File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\core\management\__init__.py", line 327, in execute django.setup() File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\user\Desktop\quora-clone-master\env\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\contrib\auth\base_user.py", line 49, in <module> class AbstractBaseUser(models.Model): RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagated to type.__new__? -
Allow End User To Add To Model, Form, and Template Django
Is there anything that someone could point me towards (a package, an example, a strategy, etc) of how I could implement the ability for an end user of my app to create a new field in a model, then add that model field to a model form and template? I’m thinking of the way that Salesforce allows users to add Custom fields. I don’t really have any start point here I am only looking to learn if/how this might be possible in Django. Thanks! -
Using Django for incoming Streaming API?
We would like to implement a connection to a streaming API and store the continuously incoming information in a relational database. There will be roughly 50,000 database inserts per day. We prefer to implement this in Django. In short, we will create a service that establishes a GET connection to a server and this connection never closes. However, is Django suited for these purposes? In other words, where should this service best be implemented in Django, because it does not contain a view. Likewise, how does Django deal with these concurrent activities? Wouldn't this service block the Django app from doing anything else? Thanks! -
Django model not working in admin section on Heroku
I want to deploy a new model on my heroku app, for making comments in my blog app. For this, I created a new class 'Comment' in models.py and added it it also to admin.py. Then i migrated it locally: manage.py makemigrations manage.py migrate Next i uploaded it to heroku: git add -A git commit "add model" git push heroku master and migrated it there: heroku run python manage.py migrate But then it gives me following message: psycopg2.errors.UndefinedTable: table 'blog_comment' does not exist I tried to use the hint heroku run python manage.py migrate --fake It seems that with this it will create the model and show it in the admin section. But when I click on 'Comment' there, it will just give out "Error 500". So it is not possible for me to access the Comment model. On my local computer it all works without a problem, but on heroku I think i forgot something. Can anyone help? Best regards -
how specify the that the model information get only selected model
i have four model shop , products, customer,order how arrange them so that shop as user if the customer search the shop category then list of shop present and when he select the shop then the products of the shop present and he place order and fill his information then shop get the customer information and product details he have order -
Cant install Django-admin >> cl.exe error failed with exit status 2
I am trying to install django-admin but run into the following error: C:\Users\Jonas\Desktop\CFD\CFD>pip install django-admin Collecting django-admin Using cached django_admin-2.0.1-py2.py3-none-any.whl (7.6 kB) Collecting django-excel-response2>=3.0.0 Using cached django_excel_response2-3.0.2-py2.py3-none-any.whl (4.4 kB) Collecting django-excel-base>=1.0.4 Using cached django_excel_base-1.0.4-py2.py3-none-any.whl (4.0 kB) Requirement already satisfied: django-six>=1.0.4 in c:\users\jonas\appdata\local\programs\python\python38-32\lib\site-packages (from django-excel-response2>=3.0.0->django-admin) (1.0.4) Collecting screen Using cached screen-1.0.1.tar.gz (8.6 kB) Requirement already satisfied: xlwt in c:\users\jonas\appdata\local\programs\python\python38-32\lib\site-packages (from django-excel-base>=1.0.4->django-excel-response2>=3.0.0->django-admin) (1.3.0) Requirement already satisfied: pytz in c:\users\jonas\appdata\local\programs\python\python38-32\lib\site-packages (from django-excel-base>=1.0.4->django-excel-response2>=3.0.0->django-admin) (2019.3) Building wheels for collected packages: screen Building wheel for screen (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\jonas\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Jonas\\AppData\\Local\\Temp\\pip-install-qzvcu9nl\\screen\\setup.py'"'"'; __file__='"'"'C:\\Users\\Jonas\\AppDat a\\Local\\Temp\\pip-install-qzvcu9nl\\screen\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Jonas\AppData\Local \Temp\pip-wheel-oenuazzg' cwd: C:\Users\Jonas\AppData\Local\Temp\pip-install-qzvcu9nl\screen\ Complete output (19 lines): running bdist_wheel The [wheel] section is deprecated. Use [bdist_wheel] instead. running build running build_py creating build creating build\lib.win32-3.8 creating build\lib.win32-3.8\screen copying screen\compat.py -> build\lib.win32-3.8\screen copying screen\old_str_util.py -> build\lib.win32-3.8\screen copying screen\__init__.py -> build\lib.win32-3.8\screen running build_ext building 'screen.str_util' extension creating build\temp.win32-3.8 creating build\temp.win32-3.8\Release creating build\temp.win32-3.8\Release\source C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.25.28610\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ic:\users\jonas\appdata\local\programs\python\python38-32\include -Ic:\users\jonas\appdata\local\programs\python\p ython38-32\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.25.28610\include" /Tcsource/str_util.c /Fobuild\temp.win32-3.8\Release\source/str_util.obj str_util.c c:\users\jonas\appdata\local\programs\python\python38-32\include\pyconfig.h(59): fatal error C1083: Datei (Include) kann nicht ge”ffnet werden: "io.h": No such file or … -
Can anyone explain this django model?
I trying to learn django. I am trying to understand slug and collected few lines of code which generates url with pk & title text. It works fine but cann't understand everything. Can anyone give me a little explanation of this one? class ArticlePkAndSlug(models.Model): title = models.CharField(max_length=settings.BLOG_TITLE_MAX_LENGTH) slug = models.SlugField(default="", editable=False, max_length=settings.BLOG_TITLE_MAX_LENGTH) def get_absolute_url(self): kwargs = {"pk": self.id, "slug": self.slug} return reverse("article-pk-slug-detail", kwargs=kwargs) def save(self, *args, **kwargs): value = self.title self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) -
How to make a dynamic countdown timer using django and javascript?
From views.py I am returning date and time to my HTML page. But unable to use that date and time to set a countdown timer using Javascript For e.g return render(request,'page.html',{'date':i.date,'time':i.time,'hours':i.hours}) time represents starting time hours represent total countdown time 'i' is python object -
Using multiple POST requests with different urls in a single page
I am trying to build a todo-list with an add/delete and completed button for each todo. I've used multiple forms and POST requests to make it work. Is there a better solution to achieve this? Current issues- page refresh after adding adds the same item to the list, page refresh after every request. views.py from django.shortcuts import render, redirect from .models import * from .forms import ListForm # Create your views here. def homePage(request): list = List.objects.all() form = ListForm() if request.method == 'POST': form = ListForm(request.POST) if form.is_valid(): form.save() context = {'list': list, 'form': form} return render(request,'todoList/home.html',context) def deleteList(request,pk): list = List.objects.get(id=pk) if request.method == 'POST': list.delete() return redirect('/') def completed(request,pk): list = List.objects.get(id=pk) if request.method == 'POST': print(list.completed) if list.completed == False: list.completed = True else: list.completed = False list.save() return redirect('/') Html <h2>Todo list</h2> {% for listItem in list %} <div class="row"> <form class="bottomCont" action=" {% url 'delete_list' listItem.id %} " method="POST"> {% csrf_token %} <div class="col-sm-3"> <h4>{{ listItem }}</h2> </div> <div class="col-sm-1"> <p>{{ listItem.completed }}</p> </div> <div class="col-sm-2"> <p>{{ listItem.date_added }}</p> </div> <div class="col-sm-1"> <button type="submit" class="btn btn-danger">Delete</button> </div> </form> </div> <form action=" {% url 'completed' listItem.id %}" method="POST"> {% csrf_token %} <div class="col-sm-1"> <button type="submit" … -
Why is Django not saving to database?
I believe I have the correct code, but when I submit the form, nothing is saved to the database. I have debugged the code and the data from the form is being sent via POST, it' just that nothing is being saved to the database: views.py def sign_up_post(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user) if p_form.is_valid(): user_object = p_form.save() user_object.save() return redirect('sign_in_photo_verify') else: p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'p_form': p_form } return render(request, 'users/sign-up-post.html', context) forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image', 'city', 'state', 'zip', ] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField( default='default.jpg', verbose_name='Profile Image', max_length=255, storage=FileSystemStorage(location=UPLOAD_DIR, base_url='/media/uploads/')) verification_image = models.ImageField( default=None, null=True, blank=True, verbose_name='Verification Image', max_length=255, storage=FileSystemStorage(location=UPLOAD_DIR, base_url='/media/uploads/')) city = models.CharField(max_length=30, null=True) state = models.CharField(max_length=2, null=True) zip = models.CharField(max_length=5, null=True) approved = models.BooleanField(default=False) def is_approved(self): return self.approved def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): return super(Profile, self).save(*args, **kwargs) def verification_image_tag(self): from django.utils.html import escape from django.utils.html import mark_safe return mark_safe('<img src="%s" />' % escape(self.verification_image.url)) verification_image_tag.short_description = 'Verification Image' verification_image_tag.allow_tags = True -
I can not display bookmarks for the user (django)
I'm trying to make the function of adding and displaying bookmarks (favorites) of the user. I do the guide. What is at the moment: User bookmarks are successfully added successfully to the database I can not display the bookmarks that the user added Below I attach the code that adds a bookmark for the user. models.py Article Model: class Post(models.Model): title = models.CharField(max_length=200, unique=True,) slug = models.SlugField(max_length=200, unique=True,) content = RichTextUploadingField() def get_bookmark_count(self): return self.bookmarkarticle_set.all().count() # def __str__(self): return self.title Abstract model: class BookmarkBase(models.Model): class Meta: abstract = True user = models.ForeignKey(User, verbose_name="user") def __str__(self): return self.user.username Inherited Model: class BookmarkArticle(BookmarkBase): class Meta: db_table = "bookmark_article" obj = models.ForeignKey(Post, verbose_name="article") views.py class BookmarkView(View): model = None def post(self, request, pk): user = auth.get_user(request) bookmark, created = self.model.objects.get_or_create(user=user, obj_id=pk) if not created: bookmark.delete() return HttpResponse( json.dumps({ "result": created, "count": self.model.objects.filter(obj_id=pk).count() }), content_type="application/json" ) I'm trying to display bookmarks in the template that the user added: {% for bookmark in user.bookmarkarticle_set.all %} {{ bookmark.post.title }} {% endfor %} Nothing is output. What needs to be done to display the bookmarks that the user has added? I would be grateful for any help. Bookmarked guide source -
Django messages not showing up instead showing <django.contrib.messages.storage.session.SessionStorage object at 0x0000029C6456A388>
Django messages not showing up instead showing . I have tried every solution given at StackOverflow by other users but it;s not working. import os INSTALLED_APPS = [ 'crispy_forms', 'login.apps.LoginConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' -
Bulk upload of files in the admin site
Django 3.0.6 I have a model with multiple ImageFields. Could you tell me how to bulk upload them? I have tried django-bulk-admin, but it doesn't work with Django 3.0. Could you help me find such a ready made app? If it is not possible, what is the easiest solution? -
Django urls.py: passing dynamic url parameter into include()
I found in Django docs (https://docs.djangoproject.com/en/3.0/topics/http/urls/#passing-extra-options-to-include) that I can pass any constant into include() statement. Here in docs' example we are passing blog_id=3. from django.urls import include, path urlpatterns = [ path('blog/', include('inner'), {'blog_id': 3}), ] But what if I want to pass dynamic url parameter into include()? I mean something like this: from django.urls import include, path urlpatterns = [ path('blog/<int:blog_id>/', include('inner'), {'blog_id': ???}), ] Is it possible? -
Any Better Way to get the Print Result For Django Model
Any Better Way to Write This Code For Django Model A few subtleties that are worth mentioning: class Model_a(models.Model): a_Name = models.CharField(max_length=200, null=True, blank=True) a_city = models.CharField(max_length=200, null=True, blank=True) a_address = models.CharField(max_length=200, null=True, blank=True) class Model_b(models.Model): Model_a= models.ForeignKey(Model_a, on_delete=models.CASCADE,null=False) b_pin = models.CharField(max_length=200, null=True, blank=True) b_zip = models.CharField(max_length=200, null=True, blank=True) b_distance = models.CharField(max_length=200, null=True, blank=True) qs = Model_a.objects.filter( model_b__b_pin='11', a_city ='101') for i in qs: for b in i.model_b_set.all(): print(b.b_zip + "------" + i.a_city)```