Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding field to ManyToMany relationship Django ORM
So I'm building out a database where I need to have a field related to a specific ManyToMany relationship, but I don't know how to translate this into the Django ORM. For example, I have multiple Articles that can go with multiple Publications, but I want to see which article got the most views. I figure that I could build the database like so: +------------+--------+--------+-------+ | art_pub_id | art_id | pub_id | views | +------------+--------+--------+-------+ | 101 | 201 | 301 | 6 | +------------+--------+--------+-------+ | 102 | 201 | 302 | 4 | +------------+--------+--------+-------+ | 103 | 202 | 301 | 8 | +------------+--------+--------+-------+ Or I could do this +------------+--------+--------+ | art_pub_id | art_id | pub_id | +------------+--------+--------+ | 101 | 201 | 301 | +------------+--------+--------+ | 102 | 201 | 302 | +------------+--------+--------+ | 103 | 202 | 301 | +------------+--------+--------+ +----+------------+-------+ | pk | art_pub_id | views | +----+------------+-------+ | 1 | 101 | 6 | +----+------------+-------+ | 2 | 102 | 4 | +----+------------+-------+ | 3 | 103 | 8 | +----+------------+-------+ I'm struggling with how to translate this to the Django ORM. I have the Article with the ManyToManyField pointing to the Publication, but I … -
object has no _state [duplicate]
This question already has an answer here: Object has no attribute _state 2 answers In my Django app I have model with "init" (I know it isn't recomended): class Voivodeship(models.Model): name = models.CharField(max_length=20, primary_key=True) def __init__(self, name): super(Voivodeship, self).__init__() self.name = name I also have script to build my database from raw data: voivodeships[name] = models.Voivodeship(name) voivodeships[name].save() But when I try to interpret it in manage.py (using exec), it returns error: 'Voivodeship' object has no attribute '_state' And I don't know what's going on. Can you suggest me any solution? -
Continue after Try has failed
I have a function: def save_to_models(all_item_tags): from article.models import Articles for item in all_item_tags: newobj = Articles() try: newobj.pub_date =item.contents[9].contents[0] except: continue try: newobj.title =item.contents[1].contents[0] except: continue try: newobj.description =item.contents[5].contents[0] except: continue try: newobj.image =get_the_picture(item.contents[7]) except: continue newobj.save() each model has unique=True so I'm using try, except to skip over the error I get when its trying to input a data that's already in the database. How can I condense this code? I feel like its a lot of unnecessary lines of code. -
Pushing Django Application to Heroku References Wrong Settings File
I have a settings file for production purposes. Despite setting DJANGO_SETTINGS_MODULE heroku config variable to the production settings file, every time I try to push the app to heroku using git I get the same build error. In the error below, it is referencing a the base level settings file. Even if I replace the base setting file with the entire production settings, the build process still references that initial setting file as evidenced by the SECRECT_KEY. The production file should have: SECRECT_KEY=os.environ['SECRET_KEY'] Why does heroku make referece to this?: "/tmp/build_455cb59c844c744adf73dd9e52dd903c/canvas/settings.py", line Instead of: remote: File "/tmp/build_455cb59c844c744adf73dd9e52dd903c/canvas/settings.py", line 24, in <module> remote: SECRET_KEY = os.environ['CANVAS_KEY'] remote: File "/app/.heroku/python/lib/python3.6/os.py", line 669, in __getitem__ remote: raise KeyError(key) from None remote: KeyError: 'CANVAS_KEY' Heres the entire trace $ git push heroku master Counting objects: 1332, done. Delta compression using up to 4 threads. Compressing objects: 100% (1137/1137), done. Writing objects: 100% (1332/1332), 12.92 MiB | 209.00 KiB/s, done. Total 1332 (delta 672), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.1 remote: -----> Installing pip remote: -----> Installing requirements with pip remote: Collecting dj-database-url==0.4.2 (from -r /tmp/build_455cb59c844c744adf73dd9e52dd903c/requirements.txt (line 1)) remote: … -
Django 1.11 URL Deprecation Warning
We're trying to update Django from 1.10 to 1.11, however; whenever we run our tests, we're getting a deprecation warning. django.utils.deprecation.RemovedInDjango20Warning: Passing a 3-tuple to django.conf.urls.include() is deprecated. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead. This occurs because of this line in our urls.py file. url(r'^admin/', include(admin.site.urls)), If we we comment out this line in our code, the tests run fine. -
Django: one url search in two models (cbv)
Using Django, I'm looking for a way to use one url patern (with slug) to query one model and if nothing is found query a second model. I'm using Class Based Views. I am following this answer, and the next View is being called. But then I get the following error: "Generic detail view must be called with either an object pk or a slug." I can't figure out how to pass the slug to the next View. My url: url(r'^(?P<slug>[-\w]+)/$', SingleView.as_view(), name='singleview'), My CBV's: class SingleView(DetailView): def dispatch(self, request, *args, **kwargs): post_or_page_slug = kwargs.pop('slug') if Page.objects.filter(slug=post_or_page_slug).count() != 0: return PageDetailView.as_view()(request, *args, **kwargs) elif Post.objects.filter(slug=post_or_page_slug).count() != 0: return PostDetailView.as_view()(request, *args, **kwargs) else: raise Http404 class PageDetailView(DetailView): model = Page template_name = 'page-detail.html' class PostDetailView(DetailView): model = Post template_name = 'post-detail.html' -
Google Maps bad handshake
I'm getting the following error [Errno socket error] [Errno 0] Error This is on a Python/Django project and is coming on the second of these 2 lines of code: url = 'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins='+request.session['postcode']+'&destinations='+s.post_code+'&key='+GOOGLE_MAPS_KEY result = simplejson.load(urllib.urlopen(url)) If I then F5 it runs through the code fine. It also works when I run it from my development server. This is happening on the Apache server. I've no idea what it means. Here's the traceback if it helps: Traceback: File "/var/www/ctl/env/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/var/www/ctl/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/var/www/ctl/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/ctl/ctl/booking/views.py" in booking3 138. result= simplejson.load(urllib.urlopen(url)) File "/usr/lib/python2.7/urllib.py" in urlopen 87. return opener.open(url) File "/usr/lib/python2.7/urllib.py" in open 213. return getattr(self, name)(url) File "/usr/lib/python2.7/urllib.py" in open_https 443. h.endheaders(data) File "/usr/lib/python2.7/httplib.py" in endheaders 1053. self._send_output(message_body) File "/usr/lib/python2.7/httplib.py" in _send_output 897. self.send(msg) File "/usr/lib/python2.7/httplib.py" in send 859. self.connect() File "/usr/lib/python2.7/httplib.py" in connect 1278. server_hostname=server_hostname) File "/usr/lib/python2.7/ssl.py" in wrap_socket 353. _context=self) File "/usr/lib/python2.7/ssl.py" in __init__ 601. self.do_handshake() File "/usr/lib/python2.7/ssl.py" in do_handshake 830. self._sslobj.do_handshake() Exception Type: IOError at /booking/booking3/2017-04-27/evening/ Exception Value: [Errno socket error] [Errno 0] Error Can anyone point me in the right direction to sort this please. -
IntegrityError: null value in column.. Django testing save method paradox
I'm writing an addition to a view that allows users to upload files, which works perfectly in when I test it using runserver. However, when I using django testcase, I get IntegrityError: null value in column "created_at" violates not-null constraint, where created_at is a DateTimeField. class Proposal(IsPrimeMixin, PSortMixin, models.Model): number = models.OneToOneField(ProjectNumber, on_delete=models.CASCADE, primary_key=True) created_at = models.DateTimeField(auto_now_add=True) ... The paradox is that where the IntegrityError error is being raised from is the parent save method. ... File "/Users/feldman/workspace/intranet/proposals/models.py", line 329, in save super(Proposal, self).save(*args, **kwargs) ... However, according to django this field should be null since auto_now fields are set in the pre_save. This is reiterated when I use runserver; self.created_at is null until after line 329 where the parent save method is called. Only after that does it have a value. > /Users/feldman/workspace/intranet/proposals/models.py(329)save() (Pdb) self.created_at (Pdb) next > /Users/feldman/workspace/intranet/proposals/models.py(330)save() -> next_number.assigned_at = timezone.now() (Pdb) next > /Users/feldman/workspace/intranet/proposals/models.py(331)save() -> next_number.save() (Pdb) self.created_at datetime.datetime(2017, 4, 26, 18, 45, 40, 65870, tzinfo=<UTC>) Hence, why is an IntegrityError being raised at the point where in non-test cases is normally populated? I am running Django 1.10 The tests: class ProposalTests(TestCase): def setUp(self): ... self.form_data = { 'city': 'Test City', 'gng_chance_of_winning': 'high', 'gng_effort_required': 2, 'market_area': … -
Updating Django Models via Admin with Method
I have an app whereby a staff can approve and reject an entry. And this can be done via Django Admin. My problem is whenever I make changes and click on the Approve button to approve the entry, it will only tick the is_approve field and the changes I made won't reflect. Tried different methods but keep on getting different issues. I want the changes to reflect and the is_approve boolean field should be ticked. Admin.py class NationAdmin(admin.ModelAdmin): change_form_template = 'admin/exapp/nation/change_form.html' def get_urls(self): urls= super(NationAdmin, self).get_urls() custom_urls= [ url( r'^approve/(?P<nation_id>\d+)/$', self.admin_site.admin_view(self.u_moderation), name='u_moderation'), url(r'^reject/(?P<nation_id>\d+)/$', self.admin_site.admin_view(self.u_rejection), name='u_rejection'), ] return custom_urls + urls list_filter=['list_date','is_approve','is_rejected'] exclude=['slug'] def change_view(self, request, nation_id, form_url='', extra_context=None): self.nation_id = nation_id return self.changeform_view(request, nation_id, form_url, extra_context) #for moderation success def u_moderation(self, request, nation_id=None): mnation= self.get_object(request, self.nation_id) mnation.is_approve=1 mnation.save() self.message_user(request, 'Viola, Entry approved!') url='/' return HttpResponseRedirect(url) #for rejection def upon_rejection(sefl, request, nation_id): return 'No error' #for plugging links in admin change form with context def render_change_form(self, request, context, *args, **kwargs): nation= self.get_object(request, self.nation_id) context.update({'nation':nation}) return super(NationAdmin, self).render_change_form(request, context, *args, **kwargs) change_form.html {% block submit_buttons_bottom %} <div class="submit-row"> {% if nation.is_approve %} <p>pass</p> {% else %} <a href="{% url 'admin:u_moderation' nation.id %}" class="historylink"> <input type="button" value="{% trans 'Approve' %}" name="_approvebutton" /></a> <input … -
TweepError at [{u'message': u'Query parameters are missing.', u'code': 25}]
I am building an application in django where if user enters some hashtag in a form field, it takes the hashtag value, displays bunch of tweets on the html page and classifies them, however i'm getting this error when i try opening "http://127.0.0.1:8000/hashtag/" TweepError at /hashtag/ [{u'message': u'Query parameters are missing.', u'code': 25}] I thought that this might have to do something with an empty formfield when users enters nothing, so i tried hard-coding the form field with "#trump" if theres no hashtag, still i am getting this error. Here's the code: def hashtag(request): title = "search via hashtags here" form_hashtag = HashtagForm(request.POST or None) instance = form_hashtag .save(commit = False) instance.save() if instance.hashtag == "": instance.hashtag = "#trump" print instance.hashtag search_number = 2 search_result = api.search(instance.hashtag, rpp=search_number) count = 0 result = [] for i in search_result: if count == 3: break classes = natural_language_classifier.classify('90e7b4x199-nlc-36073', i.text.encode('utf-8')) result.append(json.dumps(classes, indent=2)) print(json.dumps(classes, indent=2)) print count count += 1 context = {"form_hashtag":form_hashtag, "result":result, "search_result" : search_result} return render(request,'hashtag.html',context) -
Django Admin: Indent Model parent ForeignKey self relationship
Here is my model: class Company(models.Model): class Meta: verbose_name_plural = "companies" name = models.CharField(max_length=30) parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return 'Company: %s' % self.name Is there a way to modify the def __str__ method in order to display the children with a - or indent, depending on the relationship to it's parent? -
Python nested loop calculate sum
I have: models.py class Plant(models.Model): plant_name = models.CharField() multiplier = no_recording = models.PositiveIntegerField(default=1) class Recording(models.Model) plant = models.ForeignKey(Plant, on_delete=models.CASCADE) no_recording = models.PositiveIntegerField(default=1) def x(self): return self.no_recording*self.plant.multiplier I need: the sum of x for every plant. What I tried in my view is this but it does not. I get the 'Recording' object has no attribute 'aggregate' views.py def home(request): plants = Plant.objects.all() total_recording_per_plant = [] for plant in plants for recording in plant.recording_set.all(): total_recording_per_plant.append(recording.aggregate(sum=Sum('x'))) But I get the 'Recording' object has no attribute 'aggregate' -
Specify sql expression as column name in a django orm query
Look at this query: select 'DEFAULT_STRING' as category from foo Here, we don't really have the column category in the table, but we just use a string literal to represent this column value in all rows returned by the query. In place of a string literal, we could have any valid SQL expression above. Is there some way to have this query in the django ORM? -
Default values in per app django-settings
I've always wondered what is the best way to have per app settings.py files. In a way such as the configuration related to the app can be either on the app settings.py file on in the proyect settings.py file. I'm asking this right now because I'm planning on releasing an app I've developed, and I want it to be reusable. So in the app/settings.py file I'd put the default configuration values. More precisely, I have an emails app, which is that I want it to be reusable. The structure is as follows: - emails - settings.py - tasks.py - ... - my_project - settings.py In the emails/settings.py file I have the default values for the config params: USE_EMAIL_DIGEST = True EMAIL_DIGEST_PERIOD = 24*3600 Then, in my_project/settings.py I override some of those params: EMAIL_DIGEST_PERIOD = 12*3600 What is the best option to access EMAIL_DIGEST_PERIOD param from emails/tasks.py file? Currently I'm doing: from django.conf import settings import emails.settings as esettings getattr(settings, "EMAIL_DIGEST_PERIOD", esettings.EMAIL_DIGEST_PERIOD) But I think is is very verbose -
"Could not wait on event None" message in IIS log when running Django
I am running a Django site using IIS and recently I'm having long delays and 500 error pages. To find the problem, I was checking the log file of IIS and I found the message: Could not wait on event None Is it normal? Is it an error? -
Django template not found but file exist
I have some third-part library, templates from that library is diplayed by default. I want to replace layout template, from which all other start inheritance. So, in my local app I create new layout.html file, which contents {% extends 'library:layout.html' %} But in that case I've got TemplateDoesNotExist at /test-url/ test.html But still Template-loader postmortem display, that it can find file: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: /path/to/app/templates/test.html (File does not exist) Using loader django.template.loaders.app_directories.Loader: /path/to/library/app1/templates/test.html (File does not exist) /path/to/library/app2/templates/test.html (File does not exist) /path/to/library/app3/templates/test.html (File exists) So, in library app3 Django found template, but for some reason do not use it. Can you help with this issue? Thanks. -
using ajax request to get json from django and create graph in d3.js
I'm trying to serve dynamic content using AJAX calls. views.py: def index(request): qs = DCPOWERSTATS.objects.all().values('ITPOWER','AVAILABLEPOWER').order_by('-TS')[0] return JsonResponse(dict(qs)) index.html: <!DOCTYPE html> <meta charset="utf-8"> <body> <script src="http://d3js.org/d3.v3.js"></script> <script> $.ajax({ url: "http://127.0.0.1:8000/", contentType: "application/json; charset=utf-8", dataType: 'json', async: true, {# data:"{}",#} success: function (data) { draw_meter(data); } }); function draw_meter(dataset) { var width = 960, height = 500, twoPi = 2 * Math.PI; {# var dataset = {{ data_json | safe }};#} var arc = d3.svg.arc() .innerRadius(170) .outerRadius(220) .startAngle(0); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); var meter = svg.append("g") .attr("class", "season-progress"); var background = meter.append("path") .datum({endAngle: twoPi}) .style("fill", "#ddd") .attr("d", arc); var foreground = meter.append("path") .datum({endAngle:0}) .style("fill", "orange") .attr("class", "foreground") .attr("d", arc); foreground.transition() .duration(1000) .ease("linear") .attrTween("d", function(d) { var interpolate = d3.interpolate(d.endAngle, twoPi * dataset["ITPOWER"] / dataset["AVAILABLEPOWER"]) return function(t) { d.endAngle = interpolate(t); return arc(d); } }); var text = meter.append("text") .attr("text-anchor", "middle") .attr("dy", ".35em") .attr("font-size", "24") .text('USED '+dataset["ITPOWER"]); } </script> -
Rendering html content in xhtml2pdf.pisa pdf generator
Rendering html content in xhtml2pdf.pisa pdf generator showing the html tags itself, data = {'terms_condition_content':'Hello <b>world</b>'} template = get_template('agreement_terms.html') html = template.render(Context(data)) file = open("agreement_terms.pdf", "w+b") pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') The generated pdf file having content as - Hello <b>world</b> Please suggest -
Simple app in Django. How to connect to an existing database and query it?
I am new to Django; intermediate in Python3.6. Now, I've created a basic Django app which displays index.html. Now, I want to create a very simple form in index.html which will query the database and print the results in the same form. I already have the postgresql database in my local with all the data needed; it is very simple with just one table (right now, my Django app is connected to the default sqlit3 db). Where do I go about creating the query to fetch the data and populate it? -
Django Admin Page with Inline Model Loads Very Slowly
I have a Django admin page for a model with a single inline model. When the inline model has many items (like 75), the page loads very slowly (on the order of 30 seconds). This is true even if I exclude all of the fields on the inline model, having it just render the name. Removing the inline model causes the page to load very quickly (in seconds). How can I have this page load faster? -
six: cannot import name python_2_unicode_compatible
With six 1.10.0 installed under Python and pip 2.6, an old Django 1.0.4 app is not able to import python_2_unicode_compatible even though it finds six 1.10.0 just fine: >>> import six >>> six.__version__ '1.10.0' >>> from six import python_2_unicode_compatible >>> I am tasked to move a very old site that was running django 1.0.4 (you read that right, 1.0.4) and django_cms 2.0.0 Alpha to a new server. The old server croaked, so all I have is the backup of the main website files and dependencies that were installed long ago. I am Dockerizing it to help document and deploy this in the future. Ubuntu 14.04 Python 2.6 (same results with 2.7) Django 1.0.4 (installed via local zip) django_cms 2.0.0a0 (installed via local zip) I have tried Apache mod_wsgi, gunicorn (pip2.6 installed) and currently using uwsgi (preferred, pip2.6 installed) to load the app. Nginx is running in another Docker container with proxy_pass, and will the frontend proxy and TLS. uwsgi starts the site up with the custom wsgi. Upon loading the / index page, I had many import errors. Slowly, I am resolving each and every one of them (mostly related to the Django "MIDDLEWARE_CLASSES", which I have yet to find … -
POST json array and get response as json array
my client is sending me a POST with a json-array and is awaiting a response with the complete details of the requested data. I have no problems with single requests and single responses, but to minimize the overhead, I'd like to process an array. my models.py class RoFile(models.Model): user = models.ForeignKey('auth.User', null=True) filename = models.CharField(max_length=120, null=True) deleted = models.BooleanField(default=False) info = models.CharField(max_length=120, null=True) md5check = models.CharField(max_length=120, null=True) one try of my serializer: class RoFileSerializer(serializers.ModelSerializer): deleted = serializers.ReadOnlyField(required=False) user = serializers.ReadOnlyField(required=False) info = serializers.ReadOnlyField(required=False) class Meta: model = RoFile fields = ( 'filename', 'md5check', 'deleted', 'user', 'info', ) def create(self, validated_data): return RoFile(**validated_data) on try of my views: @api_view(['POST']) def rofile_detaillist(request, format=None): data = JSONParser().parse(request) serializer = RoFileSerializer(data=data, many=True) if serializer.is_valid(): json_add = [] for x in serializer.validated_data: try: rofile = RoFile.objects.filter(md5check=x['md5check']) except ObjectDoesNotExist: continue *invalid code here* return Response(jsonarraywithallinfos) else: return Resonse(status=status.HTTP_400_BAD_REQUEST) another view try: class RoFileDetailList(viewsets.ModelViewSet): model = RoFile serializer_class = RoFileSerializer(many=True) def get_queryset(self): return Rofile.objects.filter(md5check=self.request.data['md5check']) a POST example: {"filename": "filename1.exe", "md5check": "f8541061779b1efc5c30c4783edfb8f8"}, {"filename": "filename2.exe", "md5check": "16cdac5eb0ec829c2e2c199488681f6e"} what I need as a response back: {"filename": "filename1.exe", "md5check": "f8541061779b1efc5c30c4783edfb8f8", user: "testuser1", deleted: "True", info: ""}, {"filename": "filename2.exe", "md5check": "16cdac5eb0ec829c2e2c199488681f6e", user: "testuser1", deleted: "False", info: ""} Sorry for the invalid code … -
How to properly access data from the django database?
I have been trying to generate a list of books that are not been reviewed by a user, ie the books for which he/she has not written a review for. Here are the essential details from my models.py: class book(models.Model): name = models.CharField(max_length=100) isbn = models.CharField(max_length=15) author = models.CharField(max_length=120) year = models.CharField(max_length=15) genre_name = models.IntegerField() rating = models.IntegerField() description = models.CharField(max_length=2000) img = models.ImageField() def __str__(self): return self.name class reviews(models.Model): name = models.CharField(max_length=150) bookid = models.IntegerField() review = models.CharField(max_length=750) rating = models.IntegerField(default=0) def __str__(self): return self.name So, I have been trying to first get the books that the user has reviewed something like this: books1 = reviews.objects.filter(name=username) And to get the database of the books, I am doing the following: allb = book.objects.all() Initially, I just randomly generated 5 numbers in the range(1,132) and stored them in a array randb, something like this: randb = [] for i in range(0,5): randb.append(randint(1,132)) And then later linking those generated numbers to the book database that I retrieved in allb in the HTML part. My main concern is when I do that, I end up getting the books which are already reviewed by the user, simply because I have not given any condition … -
Django - serving STATIC_FILES in production get ERR_CONNECTION_REFUSED
I just upload my Django app to the server (WS 2016) but, after following a lot of SO answers and read documentation, I am not able to access static files. The code has been deployed in folder C:/www for now, until I set up Apache. I am still waiting for the domain so I am using the server machine ip. My STATIC_FILES configuration in settings.py: STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATIC_ROOT = os.path.join(BASE_DIR, "static_root_content/") STATIC_URL = 'http://server_ip/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] I execute python manage.py collectstatic and the STATIC_FILES are copied to c:/www/static_root_content with read and execution permissions When I try to access the web from other machine via http://server_ip/myapp, no static files are loaded, it is just HTML with django the functionality. Using Chrome I see the error: GET http://server_ip/static/myapp/css/jquery-ui.css net::ERR_CONNECTION_REFUSED and so on... but those files are in the folder, as I said Any ideas? Is this solved when deploying in Apache? Is this a problem with my settings? Thanks -
Filter by related field using custom QuerySet in Django
Let's say I have two models: Book and Author class Author(models.Model): name = models.CharField() country = models.CharField() approved = models.BooleanField() class Book(models.Model): title = models.CharField() approved = models.BooleanField() author = models.ForeignKey(Author) Each of the two models has an approved attribute, which shows or hides the object from the website. If the Book is not approved, it is hidden. If the Author is not approved, all his books are hidden. In order to define these criteria in a DRY manner, making a custom QuerySet looks like a perfect solution: class AuthorQuerySet(models.query.QuerySet): def for_site(): return self.filter(approved=True) class BookQuerySet(models.query.QuerySet): def for_site(): reuturn self.filter(approved=True).filter(author__approved=True) After hooking up these QuerysSets to the corresponding models, they can be queried like this: Book.objects.for_site(), without the need to hardcode all the filtering every time. Nevertheless, this solution is still not perfect. Later I can decide to add another filter to authors: class AuthorQuerySet(models.query.QuerySet): def for_site(): return self.filter(approved=True).exclude(country='Problematic Country') but this new filter will only work in Author.objects.for_site(), but not in Book.objects.for_site(), since there it is hardcoded. So my questions is: is it possible to apply a custom queryset of a related model when filtering on a different model, so that it looks similar to this: class BookQuerySet(models.query.QuerySet): def …