Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Field 'id' expected a number but got 'autobiography'
I am working on a project that allows me to upload books to database and sort them by them their collection. The problem is that whenever i upload and try to filter out books from a particular collection i get the error Field 'id' expected a number but got 'autobiography' models.py class BookDetails(models.Model): collections = models.CharField(max_length=255, choices=COLLECTION, default="") class Meta: verbose_name_plural = "BookDetails" def __str__(self): return self.collections class Books(models.Model): """ This is for models.py """ book_title = models.CharField(max_length=255, default="", primary_key=True) book = models.FileField(default="", upload_to="books", validators=[validate_book_extension], verbose_name="books") collection = models.ForeignKey(BookDetails, on_delete=models.CASCADE, default="") class Meta: verbose_name_plural = "Books" def __str__(self): return self.book_title forms.py class BookInfo(forms.ModelForm): class Meta: model = BookDetails fields = ["collections",] class BookFile(BookInfo): book = forms.FileField(widget = forms.ClearableFileInput(attrs={"multiple":True})) class Meta(BookInfo.Meta): fields = BookInfo.Meta.fields + ["book",] views.py def books(request): if request.method == "POST": form = BookFile(request.POST, request.FILES) files = request.FILES.getlist("book") try: if form.is_valid(): collection = form.save(commit=False) collection.save() if files: for f in files: names = str(f) name = names.strip(".pdf") Books.objects.create(collection=collection, book_title=name, book=f) return redirect(index) except IntegrityError: messages.error(request, "value exist in database") return redirect(books) else: form = BookFile() return render(request, "books.html", {"form":form}) def test(request): data = Books.objects.filter(collection="autobiography") template = loader.get_template('test.html') context = {"data":data} return HttpResponse(template.render(context, request)) so basically what i am trying … -
Django Model Data Only To XML
I have this simple model class TestData(models.Model): rcrd_pk = models.AutoField(primary_key=True) Name = models.CharField(max_length=50) desc = models.CharField(max_length=300, blank=True, null=True) I want to get XML of model data. so I have written this code from sms_api.models import TestData from django.core import serializers data = TestData.objects.all() XmlData = serializers.serialize("xml",data) print (XmlData) This code Export XML like this: <?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"> <object model="sms_api.testdata" pk="1"> <field name="Name" type="CharField">Roqaiah</field> <field name="desc" type="CharField">Rogaiah is Old Arabic Name</field> </object> <object model="sms_api.testdata" pk="2"> <field name="Name" type="CharField">Khadeejah</field> <field name="desc" type="CharField">Kahdejah is an Arabic Name</field> </object> </django-objects> This way exported the Model with datatypes and others unwanted deteails. I want the ouput to be simple like so <?xml version="1.0" encoding="utf-8"?> <django-objects"> <object> <Name>Roqaiah</Name> <desc>Rogaiah is Old Arabic Name</desc> </object> <object> <Name>Khadeejah</Name> <desc>Kahdejah is an Arabic Name</desc> </object> </django-objects> The last Thing if I can change the tags of the xml, so those tags <django-objects> <object> can be <RowSets> <Row> -
How to give a post (in a forum) a tag (django-taggit) with checkboxes?
In my Web Forum I have an add Post Page it looks like this: How can I get all clicked tags as a django-taggit object or whatever then send them to my backend and save them in the database? My views.py looks like that: def post_question_tags(request): current_user = request.user if request.method == "POST": Post.objects.create(title = request.POST["title"], description = request.POST["description"], tags = request.POST["tags"], author = current_user) all_tags = Tag.objects.all() return render(request, "post_question_tags.html", {'all_tags' : all_tags, 'current_user': current_user}) My Template <div class="tags"> {% for tag in all_tags %} <div class="tag"> <p class="tag-title">{{ tag.name }}</p> <input type="checkbox" class="checkbox-button" name="checkboxes" value="{{ tag.name }}" /> <p class="description">{{ tag.description }}</p> </div> {% endfor %} </div> -
class "is not defined" in django models that rely on eachother
I have two classes in my models.py. If I change the order I define the classes it makes no difference and at least one of them give an error about something not being defined. class Item(models.Model): offers = models.ManyToManyField(Bid) class Bid(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) -
How to fix MultiValueDictKeyError in django
This is my form <h1>ADD LIST</h1> <form action="addList/" method="post"> {% csrf_token %} <div class = "container"> <label>List Name</label><br> <input name="listname" class= "listNamec"><br><br></input> <label>List title</label><br> <input name="listtitle" class= "listTitlec"><br><br></input> </div> </form> And this my function def addList(response): listname = response.POST['listname'] list.name = listname list.save() return render(response, 'main/index.html', {}) error : raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'listname' i need to add these to Todolist database, and not workin :( -
Django Channels with Angular 14 Frontend
is there a way to create a socket with django and a angular 14 frontend? I've tried that with ngx-socket-io, but its not working so far. Any ideas how to solve this issue? I need to "poll" status from multiple celery tasks, so it's not effective to call the backend n (n=quantity of tasks) every x seconds to get the latest status. -
django_quill.quill.QuillParseError: Failed to parse value
Getting an error on my local server when testing using django-quill-editior for blogs in my project. I can't find out what the following error means. "django_quill.quill.QuillParseError: Failed to parse value" I do have .html|safe at the end of my codes, and the weird thing is that this is all working in my production version. Any body else experienced this error? -
Django: How to store data in Form #1 while filling up Forms #2 and #3 and import data from Forms #2 and #3 into Form #1?
I have a Vinyl model form (Form #1) that creates vinyl with the following fields: artist (ManyToManyField), title, record label (ForeignKey), cat.number, release date, cover art, price, genre, style, tracklist, quantity, and condition. Under artist and record label there are buttons that allow the user to create new entities. When pressing the "Add new artist" button, a new form (Form #2) is shown and I would like to have the already added data in Form 1 to be preserved and get the data from Form #2 populated into Form 1. Example: The artist I'm looking for is not on the list of artists in Form 1. I click "Add new artist" and Form #2 appears. I fill in the data and when clicking submit, I get redirected to Form #1. I want this new artist to be autoselected. Then I write the title. Then I see that the record label is not on the list of record labels so I click "Add new label". Form #3 is shown and I fill in the data. When clicking the submit button I'm redirected to Form #1. I would like to have all the previously added data and also the newly generated record … -
How to pass two parameters to the url for correct operation
How to pass two parameters to the url for correct operation through views classes (It seems to me that the error in views.py , also in template).The form is also used here to convey questions, this can be seen in html, but you need to abstract from the form views.py` class Question(LoginRequiredMixin, DetailView): model = Question context_object_name = 'questions' template_name = 'question.html' def get_queryset(self): return get_object_or_404(Question, quiz__slug=self.kwargs['quiz_slug'], quiz__pk=self.kwargs['pk']) ` question.html ` {% extends 'base.html' %} {% load static %} {% block content %} {{ questions }} <form action="{% url 'questions' quiz_slug pk %}" method="post"> {% for answer in questions.answers.all %} <div class="form-group"> <input type="checkbox" id="{{ answer.pk }}" name="{{ answer.pk }}" value="{{ answer.is_correct }}"> {{ answer }} </div> {% endfor %} <input href="{% url 'home' %}" class="btn btn-info btn-block badge-success" type="submit" value="Ответить"> {% csrf_token %} </form> {% endblock content %} urls.py `` path('', views.HomeListView.as_view()), path('category/<int:pk>', views.TestsListView.as_view(), name='tests'), path('test/<slug:quiz_slug>/question/<int:pk>', views.Question.as_view(), name='questions'), ] ` models.py ` class Category(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) class Quiz(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) slug = models.SlugField(max_length=255, default='') category = models.ForeignKey(Category, on_delete=models.CASCADE) class Question(models.Model): STATUS_CHOICES = ( ('one_answer', 'One_answer'), ('multiply_answers', 'Multiply_answers') ) question = models.TextField() question_type = models.CharField(max_length=20, choices=STATUS_CHOICES) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, … -
How to disable downloading static files like pdf, videos in Django
I want to develop an application using Django DRF and react JS, the app would like udemy which should access the videos online but could not download it, I am looking for a good solution and idea to disable the file downloads. There are two kinds of files PDF VIDEO I think that I should store the file directly to database, not their path -
page not found when trying to access a site deployed on netlify
i made a project related to the creation of a book site and I uploaded it to github, then I deployed it to Netlify,iam trying to view my site ,all i see a error message Page Not Found Looks like you've followed a broken link or entered a URL that doesn't exist on this site. Back to our site If this is your site, and you weren't expecting a 404 for this path, please visit Netlify's "page not found" support guide for troubleshooting tips. what should be the reason i do everything,i by a domain i do it hen i wite index.html _redirects ama nothing this is my github rebo:https://github.com/GOCTIRONE/demo2000 and my netlify site:https://juliaxhabrahimi.cloud my deploy setings:4:58:16 PM: build-image version: 4c0c1cadee6a31c9bb8d824514030009c4c05c6a (focal) 4:58:16 PM: build-image tag: v4.15.0 4:58:16 PM: buildbot version: e6d57a43d406fdcaf8ee2df93f280acce2e07259 4:58:17 PM: Fetching cached dependencies 4:58:17 PM: Starting to download cache of 91.6MB 4:58:17 PM: Finished downloading cache in 618.519356ms 4:58:17 PM: Starting to extract cache 4:58:17 PM: Finished extracting cache in 84.726724ms 4:58:17 PM: Finished fetching cache in 759.256113ms 4:58:17 PM: Starting to prepare the repo for build 4:58:17 PM: Preparing Git Reference refs/heads/master 4:58:18 PM: Parsing package.json dependencies 4:58:18 PM: Section completed: initializing 4:58:19 PM: No … -
How to delete and update posts with a ForeignKey field?
Help! Browsed the entire internet There are two models. The Source model has a ForeignKey on the Groups table. How to properly delete or update an object from the Sources table via DeleteView and UpdateView? class Groups(models.Model): slug = models.SlugField('Url group') title = models.CharField('Name', max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse('detail_groups', kwargs={'slug': self.slug}) def get_success_url(self): return reverse('list_groups', kwargs={'slug': self.slug}) class Sources(models.Model): group = models.ForeignKey(Groups, on_delete=models.CASCADE, verbose_name='Group', blank=True, null=True,) plug = models.SlugField('Url source') title = models.CharField('Name', max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse('detail_sources', kwargs={'slug': self.group.slug, 'plug': self.plug} Clicking on a link gives a 404 error path('list_groups/<slug>/<slug:plug>update', views.UpdateSources.as_view(), name='update_sources'), Tried everything!!!! -
Can I use a prevent default at a form that uses GET as a method in the Django HTML template?
I’m looking to create a section about searching for some movies in my database, however, this section is at the bottom of my page. However, when I search and find the movie that I was looking for, the page refreshed. Also, I do not know if “GET” is the ideal method for secure sections, but I read that POST is necessary just for database changes. In this case, I just want to bring the movie corresponding to what was searched at a search bar. This is my view and I am getting the search like this, in the context, to make it easier to render. It is working ok. class MoviesPage(TemplateView): template_name = "tailwind/movies-page.html" def get_context_data(self, **kwargs): context = super(MoviesPage, self).get_context_data(**kwargs) # Top Movies' section movies = Movies.objects.filter( name__in=[ 'Oldboy', 'Parasite', 'Lady Vengeance', ] ) context['movies'] = movies # Movie search's section query = self.request.GET.get('q', default='oldboy') results = Movies/.objects.filter(Q(name__icontains=query)) context['results'] = results This is my form in my HTML template: <form action="" method="GET" id="search-package-form" > <input type="search" name="q" placeholder="oldboy" /> <div> <button type="submit" > <span>Search</span> </button> </div> </form> {% if results %} <div> {% for movie in results %} <ul> <li>{{ movie.name }}</li> </ul> {% endfor %} </div> {% else … -
Creating a new empty directory folder with the record id number on the desktop for each record added with the form in Django
First of all, my english is not very good, sorry for that. I only have one field in my model. I want to create an empty directory folder on the desktop while creating a record using the form. Since I am new to Django, I would be grateful if you could write the complete codes. Thank you very much in advance. MODELS.PY class DosyaBilgileri(models.Model): sahisAdi = models.CharField(max_length=50, verbose_name='Şahıs Adı') def __str__(self): return self.sahisAdi def delilIndex(request): VIEWS.PY def delilIndex(request): dosyaEkleFormu = DosyaBilgileriModelForm(request.POST or None, files=request.FILES or None) if dosyaEkleFormu.is_valid(): dosyaEkleFormuD = dosyaEkleFormu.save(commit=False) dosyaEkleFormuD.save() messages.add_message(request, messages.INFO, 'Dosya ekleme işlemi başarıyla tamamlandı.') return redirect('delilIndex') return render(request, 'delil/index.html', {'dosyaEkleFormu':dosyaEkleFormu }) -
Django Rest Framewrok: got KeyError when write test for creating (post) nested serializer
I'm try to write test for creating sales data keep getting KeyError: 'content' when running python manage.py test. the test is to ensure user can add/create sales data with its details (nested) with this as reference to create writeable nested serializers models.py # abstract base table for transactions class Base_transaction(models.Model): is_paid_off = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) pass class Meta: abstract = True # sales table to store surface level sales information # consist of sales_id as pk, customer_name, sub_total, discount, user_id, # total, is_paid_off, created_at, updated_at class Sales(Base_transaction): sales_id = models.BigAutoField( primary_key=True, unique=True ) customer_name = models.CharField(max_length=25, blank=True) customer_contact = models.CharField(max_length=13, blank=True) user_id = models.ForeignKey( User, on_delete=models.PROTECT, null=True, db_column='user_id' ) def __str__(self) -> str: return f'{self.sales_id} at {self.created_at} | Lunas={self.is_paid_off}' class Meta: db_table = 'sales' # sales_detail table store the detail of sales per sparepart # consist of sales_detail_id as pk, quantity, individual_price, total_price # sales_id class Sales_detail(models.Model): sales_detail_id = models.BigAutoField( primary_key=True, unique=True ) quantity = models.PositiveSmallIntegerField() is_grosir = models.BooleanField(default=False) sales_id = models.ForeignKey( Sales, on_delete=models.CASCADE, db_column='sales_id' ) sparepart_id = models.ForeignKey( 'Sparepart', on_delete=models.SET_NULL, null=True, db_column='supplier_id' ) def __str__(self) -> str: return f'{self.sales_id} - {self.sparepart_id}' serializers.py class SalesDetailSerializers(serializers.ModelSerializer): sparepart = serializers.ReadOnlyField(source='sparepart_id.name') class Meta: model = Sales_detail fields = ['sales_detail_id', … -
Can't send a post requests
Hi everyone, I'm trying to send a post request through my localhost, my data is a json object, and my following code is: result = df_yahoo.get_history_data() df_yahoo_json = result.to_json() # Convert the Dataframe to JSON headers = { "Content-Type": "application/json", } # Send the POST request with the JSON data response = requests.post('https://localhost:8000/api_yahoo', json=df_yahoo_json, headers=headers) I try to send the request, and then I got the following error: requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) I send the request through the views file in Django. After converting the Dataframe to JSON, I see that the Type of df_yahoo_json is str and not dict of JSON. I would appreciate your help, thank you. -
Django multiple sites using nginx and gunicorn
I am serving multiple websites using nginx and gunicorn and I would like to add another one. Sadly my lack of experience is limiting me, I have some experience with webdesign but always struggle on the server side...|-( (I am using Django because of my Python preference in scientific analysis). My problem: The new site seems to refer to the port used by another. Checking the gunicorn status I see that the site is running although nginx seems to be unable to refer to the correct Django folder. Could someone point me in the right direction? I have been looking around for the last hour or so... (I didn't include any code for now as I am not sure where the error might lie at this point...) -
Filter over jsonfiled with unknown keys in Django ORM
There is a model with JSONfield in Django model: class MyClass(models.Model): is_info = models.BooleanField() info = models.JSONField() The data inside table is like: is_info info false true {'key123':{'a':'1', 'b':'2', 'search_key':'text'},'key456':{'a':'1', 'b':'2', 'search_key':'another_value'}} And I need to filter somehow a query set to receive a set of rows where compound key 'search_key'='text' and not include in result values from 'info' field where 'search_key' has some other values. My keys of 'info' field (key123, key456 and etc.) are always different and I don't know the exact value. Please, help me!!!) I've tried: q = queryset.filter(info__icontains='text') but it return for me all the field info: {'key123':{'a':'1', 'b':'2', 'search_key':'text'},'key456':{'a':'1', 'b':'2', 'search_key':'another_value'}} when I need to receive only: {'key123':{'a':'1', 'b':'2', 'search_key':'text'}} -
How to use objects.filter for (one-to-many) releation
I have 3 tables: Job, Flight, and Image One job can have multiple flights and a flight can have only one job. And a flight can have many images. I get all flights related to the job using the query: flights = Flight.objects.filter(job_id=job_id) and now I want all images in those flights to call a function for all images but I couldn't implement it without a loop: for flight in flights: images = Image.objects.filter(flight=flight) data = process_images(images) I want something like: images = Image.objects.filter(flight=flights) so I call process_images only once, is that possible? -
Not able to retrieve variable in template in Django ajax call
I am trying retrieve counter value passed from view in the html template .It is coming as None, however in the view print and in ajax success log value it is coming correct. JS ajax func $(".pos").click(function(){ counter=counter+1; $(".add").html('add counter '+counter); $.ajax( { url :'page', type :'get' , data:{ quantity: counter }, success:function(response){ console.log(response); } } ); My view def page(request): counter=request.GET.get('quantity') print(counter) ## this is printing fine return render(request,'page.html',{'counter':counter}) html template <body> {{counter}} <button class="btn neg" name="neg-btn">-</button> <button class="btn add" name="add-btn" >add to box</button> <button class="btn pos" id="test" name="pos-btn">+</button> </body> getting this counter as None -
FileNotFoundError at / [Errno 2] No such file or directory while saving an image
I want to create a qr-code generator for hashed values. However, it works pretty strange, because sometimes everything works good, but sometimes it gives me an error: FileNotFoundError at / [Errno 2] No such file or directory. For example, it can save a few qr-codes and then throw that error. Here is the code: def qr_creator(request): for i in range(50): hash_uuid = uuid.uuid4 hash = Hasher.encode(self=Hasher(), password=hash_uuid, salt=Hasher.salt(self=Hasher())) data = f"{hash}" img = make(data) img_name = f"{hash}.png" img.save(str(settings.MEDIA_ROOT) + '/qr_codes/' + img_name) return HttpResponse("Done!") As I understand, the problem lies in img_name as if I change it for example, like this: img_name = f"{hash}.png", everything works as it should be. But I need my qr-codes to be named strictly as hash values. So my question is how can I fix this so I can save my qr-codes with its values? Thanks in advance -
Get serializer data by foreign key
I need to pass data from EmployeeSerializer to VacationSerializer as nested json. This is my serializer.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'first_name', 'surname', 'patronymic', 'birthday', 'email', 'position', 'phone_number') class VacationSerializer(serializers.ModelSerializer): class Meta: model = Vacation fields = ('pk', 'start_date', 'end_date', 'employee_id', 'employee') and my models.py: class Employee(models.Model): first_name = models.CharField("Name", max_length=50) surname = models.CharField("surname", max_length=50) patronymic = models.CharField("patronymic", max_length=50) birthday = models.DateField() email = models.EmailField() position = models.CharField("position", max_length=128) phone_number = models.CharField("phone", max_length=12, null=True) is_deleted = models.BooleanField(default=False) def __str__(self): return f'{self.surname} {self.first_name} {self.patronymic}' class Vacation(models.Model): start_date = models.DateField() end_date = models.DateField() employee_id = models.ForeignKey(Employee, related_name='employee', on_delete=models.PROTECT, default=-1) def __str__(self): return f'{self.start_date} - {self.end_date}' @property def date_diff(self): return (self.end_date - self.start_date).days in views.py I have this: @api_view(['GET', 'POST']) def vacations_list(request): if request.method == 'GET': data = Vacation.objects.all() serializer = VacationSerializer(data, context={'request': request}, many=True) return Response(serializer.data) I've tried this: class VacationSerializer(serializers.ModelSerializer): employee = EmployeeSerializer(read_only=True, many=True) class Meta: model = Vacation fields = ('pk', 'start_date', 'end_date', 'employee_id', 'employee') but it doesn't show me even empty nested json, it shows me only VacationSerializer data. I easily can access VacationSerializer from EmployeeSerializer using PrimaryKeySerializer or any other serializer and get nested json where VacationSerializer data is nested in EmployeeSerializer data. … -
I am getting error on user login and registration in django
Hi, I have a project with django, database mysql, I'm getting an error in user login and registration process. Could it be from the database, do I need to code it differently because it's mysql? my codes and error message are attached ` `` ` ` def signupPage(request): if request.method == "POST": Formusername = 'username' in request.POST Formemail = 'email' in request.POST Formpassword = 'password' in request.POST Formrepassword = 'repassword' in request.POST if Formpassword == Formrepassword: if User.objects.filter(username=Formusername).exists(): return render(request,"signup.html",{"error":"username already taken","username":Formusername}) else: if User.objects.filter(email=Formemail).exists(): return render(request,"signup.html",{"error":"email already taken","email":Formemail}) else: user = User.objects.create_user(username=Formusername,email=Formemail,password=Formpassword) user.save() return redirect("signin") else: return render(request,"signup.html",{"error":"passwords do not match!"}) return render(request,"signup.html") def signinPage(request): if request.method == "POST": username = 'username' in request.POST password = 'password' in request.POST user = authenticate(request,username = username,password = password) if user is not None: login(request, user) return redirect("home") else: return render(request,"account/signin.html",{"error":"username or password wrong"}) return render(request,"signin.html") def logoutPage(request): return redirect("home") ` < `ValueError at /account/signup The given username must be set Request Method: POST Request URL: http://127.0.0.1:8000/account/signup Django Version: 4.1.3 Exception Type: ValueError Exception Value: The given username must be set Exception Location: C:\Users\merte\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\models.py, line 144, in _create_user Raised during: account.views.signUpUser Python Executable: C:\Users\merte\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.0 Python Path: ['C:\\Users\\merte\\Desktop\\İş-Güç\\Orders\\order', 'C:\\Users\\merte\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\merte\\AppData\\Local\\Programs\\Python\\Python311\\Lib', … -
403 Forbidden media file django, nginx, aws
The images are not displayed in my project. If the static files. This is how my nginx configuration looks server{ listen 80; server_name domain; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /var/www/html/static/; } location /media/ { autoindex on; alias /home/user/project/var/www/html/media; } location / { include proxy_params; proxy_pass http://ip:8000; } my settings.py DEBUG = False MEDIA_ROOT ='var/www/html/media' MEDIA_URL = '/media/' the permmission this path: /home/user/project/var/www/html/media drwxrwxr-x 3 www-data www-data I need the images to be displayed to the user or other solutions with other services with aws. -
Django Models Reverse Lookup
I am trying to normalize my models in Django. I have three models as below from django.db import models class Province(models.Model): province = models.CharField(max_length=20, blank=False, null=False) def __str__(self): return province class District(models.Model): district = models.CharField(max_length=20, blank=False, null=False) province = models.ForeignKey('Province', related_name='district_province', on_delete=models.CASCADE) def __str__(self): return district class School(models.Model): school = models.CharField(max_length=20, blank=False, null=False) district = models.ForeignKey('District', related_name='school_district', on_delete=models.CASCADE) def __str__(self): return self.school When I query the school model I can get the District, My question is, is it possible to also get the province without adding it as a foreign key in the School model? if yes, how do I achieve that? The Use cases are: Query a school with all its properties including district and province. With: School.objects.all or School.objects.get/filter I can get all schools and the district details but I do not know how to reach the province model. Get all schools in a District With: School.objects.filter(district=x) I can get schools in a district with no problem here. Get all schools in a Province Say I have province ID as 2, how do I get all schools in province 2? Thanks for any help given.