Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Listing existing objects and objects search results on Django
I have the following LodgingOffer model with their respective models.Manager with the order of perform some searches using solr and haystack The LodgingOfferManager perform the active() function to retrieve the LodgingOffer active objects which are active if those have the is_taked = True class LodgingOfferManager(models.Manager): def active(self, *args, **kwargs): return super(LodgingOfferManager, self).filter(is_taked=False).filter(pub_date__lte=timezone.now()) This is the LodgingOffer model with some of their more representative fields related to my case/question def get_images_search_path(instance, filename): return '/'.join(['lodging_offer_images', instance.slug, filename]) class LodgingOffer(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ad_title = models.CharField(null=False, blank=False, max_length=255, verbose_name='Título de la oferta') photo = models.ImageField(upload_to=get_images_search_path, blank=False, verbose_name='Fotografía', null=False) pub_date = models.DateTimeField(auto_now_add=True) is_taked = models.BooleanField(_('Oferta tomada'), default=False,) objects = LodgingOfferManager() def __str__(self): return "%s" % self.ad_title To perform my searchs I have this form: class LodgingOfferSearchForm(forms.Form): query = forms.CharField(label='', widget=forms.TextInput()) In my views I have the LodgingOfferSearch view to perform the searches of this way: class LodgingOfferSearch(FormView): template_name = 'hosts/lodgingoffer_search.html' form_class = LodgingOfferSearchForm() def get(self, request, *args, **kwargs): form = LodgingOfferSearchForm(self.request.GET or None) return self.render_to_response(self.get_context_data(form=form)) # We get the active object records # I think that this is not necessary ... ? def get_queryset(self): qs = LodgingOffer.objects.active() return qs def get_context_data(self, **kwargs): context = super(LodgingOfferSearch, self).get_context_data(**kwargs) user = self.request.user form = LodgingOfferSearchForm(self.request.GET or … -
How to create multiple inner joins using Django ORM
I'm really struggling to find documentation and examples to solve the following dilemma. I have two tables, Results (which contain results of a race) and Photos (where each photo contain runners in that race). Both tables contain entrant_numbers, i.e. the number of the runner in the race and the number of the runner in the photo. In SQL I joined them like so to get the total number of photo captures per runner. SELECT * FROM photos p INNER JOIN results r ON p.EntrantNumber=r.EntrantNumber AND p.raceyear=r.raceyear WHERE r.userid=123 My models are structured like so; class Photo(models.Model): photo_id = models.AutoField(primary_key=True) url_pre_string = models.CharField("URL pre-string", max_length=255) filename = models.CharField("Filename", max_length=100) extension = models.CharField("File extensions", max_length=4) race_year = models.PositiveIntegerField("Race year", default=0) entrant_number = models.PositiveIntegerField("Entrant number", default=0) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) class Result(models.Model): results_id = models.AutoField(primary_key=True) position = models.PositiveIntegerField("Position", default=0) entrant_number = models.PositiveIntegerField("Entrant number", default=0, null=True, blank=True) firstname = models.CharField("Firstname", max_length=255) surname = models.CharField("Surname", max_length=255) team_name = models.CharField("Team name", max_length=255, null=True, blank=True) registration_number = models.PositiveIntegerField("Registration number", default=0, null=True, blank=True) category = models.CharField("Category", max_length=50, null=True, blank=True) gender = models.CharField("Gender", max_length=50, null=True, blank=True) date_of_birth = models.CharField("Date of birth", max_length=30, null=True, blank=True) no_mail = models.BooleanField("No mail", default=False) finish_time = models.CharField("Finish time", max_length=50, null=True, blank=True) chip_time … -
ValueError: invalid literal for int() with base 10 seems to be related to ForeignKey
Trying to get to the bottom of this error. Several SO questions on the subject and the answers range from: deleting previous migrations, setting default value in the model for the field, or using a GenericForeignKey. None have resolved my issue thus far. I am fairly certain the issue is related to ForeignKey and have read it uses int() by default even if the field is CharField. Here is the field in question in the model I am trying use: product_code = models.ForeignKey(Products, null=False) Here is the field in the parent model it is referring to (Products): code = models.CharField(unique=True, max_length=16) And here is the query where the issue is occurring: # returns 'A_17' product_code = Products.objects.get(id=data['product_id']).code # error triggered here: print(ProductPositions.objects.filter(product_code=product_code)) # ValueError: invalid literal for int() with base 10: 'A_17' So it appears to be string from end-to-end, but I guess with the ForeignKey "defaulting" to integer or something the issue is related to that. Not sure how to override that as something like default='' doesn't work. Not sure how to clear up the issue so thanks for the feedback. -
Doesen't work LIKE icontains
Try do search with ajax requests. prefix = str(request.POST.get('prefix')) colors = UserDataCsv.objects.filter(material__icontains=prefix).values('color') print(colors.query) But i don't get response, coz: SELECT `users_userdatacsv`.`color` FROM `users_userdatacsv` WHERE `users_userdatacsv`.`material` LIKE %ff% ORDER BY `users_userdatacsv`.`id` ASC I haven't quotes in mysq SQL reqyest %ff%, how i can fix it? Use django 1.9 -
Django/PIL: AttributeError: 'Image' object has no attribute 'read'
I'm testing example code validate image field (Django custom validation in model form for imagefield (max file size etc.)): models.py from django.db import models from filer.fields.image import FilerImageField class Event(models.Model): # (...) banner = FilerImageField(verbose_name='Banner') admin.py from django.contrib import admin from django import forms from PIL import Image from .models import Event class EventForm(forms.ModelForm): class Meta: model = Event fields = '__all__' def clean_banner(self): image = self.cleaned_data.get('banner', False) if image: img = Image.open(image) img.load() width, height = img.size max_width = 879 max_height = 392 if width > max_width or width < max_width or height > max_height or height < max_height: raise forms.ValidationError('Imagem está com dimensão incorreta: %s x %s pixels. Insira uma imagem com %s x %s pixels.' %(width, height, max_width, max_height)) # Máx 3MB if len(image) > (3 * 1024 * 1024): raise forms.ValidationError('Arquivo de imagem muito grande (máximo 3MB).') name_type, ext = image.content_type.split('/') if not (name_type == 'image' and ext.lower() in ['png', 'jpg', 'jpeg']): raise forms.ValidationError('Por favor, use imagem em formato JPG, JPEG ou PNG.') else: raise forms.ValidationError('Não foi possível ler a imagem carregada.') return image error when registering image not django-admin. Version: Pillow==4.3.0, Python==3.6 Traceback (most recent call last): File "C:\Users\Lidy Monteiro\Developer\integra-fundaj\.myvenv\lib\site-packages\PIL\Image.py", line 2534, in open fp.seek(0) … -
Finding someone to build simple Django Website
I want to create a simple website and turns out my basic html knowledge won't get the job done. I learned some basic python/django through youtube/internet research and was able to build a basic site that looks decent. The problem is I am trying to give the site search functionality and after a week of research I can't figure this part out. I wan't to be able to create multiple databases that can be searched with a search box. You enter your search keyword, it searches all databases and prints results on your screen. I got as far as creating one database but I am having trouble getting the search box to work with it. I also couldn't figure out how to add new databases. Now I've come to the realization that it might be best to have someone build a skeleton site with just the functionality that I need. I can then take care of the site's appearance. Whats the best way to go about hiring somebody and where can I find them. I'm using a windows pc not a mac therefore I would need the site to be pc friendly for editing. Using Django 2.0 and python 3.0. -
How does django testing work with running both the client and the server at once?
I'm wondering, it seems that when you run django tests, you have access to a client, which is hitting a running copy of your server. How does this work? Is it all done in a single thread? My question is motivated by the request_finished signal. I'm wondering, when you're running django tests, will request_finished call its functions before the response returns, or after? Or not at all? Please let me know if I can expand on this question in any helpful way -
refer to last available historical data
In a django project backed by a postgresql db I have two models,: class Asset(models.Model): name = models.CharField(...) class AssetHistory(models.Model): asset = models.ForeignKey('Asset', ...) timestamp = models.DateTimeField(...) value = models.IntegerField(...) Periodically some data are added to AssetHistory for some specific asset. What is the best practice to refer to the last value in AssetHistory for a specific asset? I was thinking to add 2 extra fields in Asset model and update them when a new entry is added to AssetHistory class Asset(models.Model): name = models.CharField(...) timestamp = models.DateTimeField(...) value = models.IntegerField(...) but i'm not sure this is the best choice. -
Django rest framework URL Filter - Edit/Update Instance returned via filter method
I've had success using filter_fields to return a single filtered result list. I want to update to this result. Is there a way to update a filtered single result? via a URL pattern like the below? LocalHost:8080/PriceMaster/?ISIN=aaa&valuedate=2018-01-01 I know if i use the primary key at the end of the URL instead of the filter I can update the instance. I feel I may have to make a second view (inheriting from one of these API views) with a a new url? RetrieveUpdateAPIView, RetrieveDestroyAPIView, RetrieveUpdateDestroyAPIView Is there a way to keep it within the 1 ViewSet and what might it look like? This is my current views.py class OptionMasterViewSet(TemporalModelViewSet): queryset = OptionMaster.objects.filter(vflag=1) lookup_field = 'django_id' filter_backends = (DjangoFilterBackend,) filter_fields = ('ISIN', 'ValueDate',) model = OptionMaster When I make a PUT or POST within Postman to the URL I get the error "Method Not Allowed" Thanks -
MongoDB with Django Rest Elasticsearch?
Following the Basic Usage example at http://django-rest-elasticsearch.readthedocs.io/en/latest/ from app.serializers import BlogSerializer from app.models import Blog from rest_framework_elasticsearch import (es_views, es_client, es_pagination, es_filters) from .search_indexes import BlogIndex class BlogView(es_views.ListElasticAPIView): es_client = es_client es_model = BlogIndex es_pagination_class = es_pagination.ElasticLimitOffsetPagination es_filter_backends = ( es_filters.ElasticFieldsFilter, es_filters.ElasticFieldsRangeFilter, es_filters.ElasticSearchFilter, es_filters.ElasticOrderingFilter, ) es_ordering = 'created_at' es_filter_fields = ( es_filters.ESFieldFilter('tag', 'tags'), ) es_range_filter_fields = ( es_filters.ESFieldFilter('created_at', 'created_at'), ) es_search_fields = ( 'tags', 'title', ) Gives me the stacktrace: `Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10de071e0> Traceback (most recent call last): File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File … -
manage.py runserver fails after putting custom app in middleware
Im following a guide on youtube to work with django. Unfortunately this guide is made for pre 2.0 django. So the challenge is to create a app called "posts" that can be accessed by localhost/posts. After creating the folder 'posts' and adding it to settings.py MIDDLEWARE like this: MIDDLEWARE = [ 'posts', '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', ] python manage.py runserver fails When commenting 'posts' out runserver succedes. The problem is that Im so new to all of this that I don't even know what to search for. -
Django send too many message with Messenger Bot
I tried sending a message to my Facebook account from My Facebook page, but it sends too many messages and never stop till restarting server and change views.py code. from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import requests import json @csrf_exempt def hello(request): response_msg = json.dumps({"recipient":{"id":"1786715484701833"}, "message":{"text":"hi!"}}) requests.post("https://graph.facebook.com/v2.9/me/messages?access_token=<page-access-toke>",headers={"Content-Type": "application/json"},data=response_msg) return HttpResponse("pong") When i removed headers it doesnt send any message, what is the problem about this? -
Django: Different level of logging on server and locally
I've set the logging level to INFO for loggers and handlers. Everything works as expected when I run Django on my local machine with ./manage.py runserver. However, on Apache server with WSGI, the log contains only WARNING logs. The DEBUG variable is set to True in both cases. Here is critical part of my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'normal': { 'format': '%(levelname)s %(asctime)s %(module)s %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/var/log/clawd.log', 'formatter': 'normal' }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'normal' }, }, 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'INFO', 'propagate': True } } } State of the log after GET request on the local machine: INFO 2018-01-18 22:07:38,935 basehttp "GET /case/new/doc/1 HTTP/1.1" 200 337 On the server: Any idea how could that happen? How Django even knows that it is running on a server when the DEBUG flag is still True? -
why post method looks as 'OPTIONS' in django
I simply post a file to django app which hosted in virtual machine. and request logs looks like; [18/Jan/2018 21:49:06] "OPTIONS /upload/ HTTP/1.1" 200 0 I searched and installed django-cors-headers nothing looks wrong but whats this options stuff? why django doing this? here is function in django: def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'upload.html', {'form': form}) -
Filter form field based on another form field (user selects date, then another field displays timeslots available that day)
I'm trying to filter the slot (time slot) field based off of the day field the user selects. So basically filter the slot field to only show the ones that exist on that day. I have successfully been able to filter it based off if the time slot is booked, but can not get it to dynamically filter based off the date field. I have two models. Appointment, and Calender (I refer to the rows in this table as time slots) Models class Calendar(models.model): date = models.DateField() timeslot_A = models.TimeField() timeslot_B = models.TimeField() booked = models.BooleanField(default=False) class Appointment(models.Model): """Appointment Information""" client = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) day = models.DateField(u'Day of the event', help_text=u'Day of the event') slot = models.OneToOneField(Calendar, on_delete=models.CASCADE) Forms.py class AppointmentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AppointmentForm, self).__init__(*args, **kwargs) self.fields['slot'].queryset = Calendar.objects.filter(booked=False, date=self.instance.day) #HERE^^^^^^^^^^^^^^^^ class Meta: model = Appointment fields = ['day', 'slot', 'notes', 'recurring', 'extras'] widgets = { 'day': forms.DateInput(attrs={'id': 'datepicker', 'type': 'select'}), } I know how to achieve this using jquery, but I'm pretty sure that't not ideal since it's filtered on the front end. -
Pass Django Variable Via Javascript
I'm new to Javascript, and trying to figure out how to get the value of a variable in my HTML form. I have the following code kind of working, I put an alert in to test my logic and the else statement is working, but I can't seem to figure out how to get Javascript to submit my form if the value is set to on. I know my value is being interpretted correctly as I tested it with an alert as well. It just doesn't seem to want to submit the form. I have looked through SO and it seems that the Javascript submit syntax might have changed? Here is my Javascript function: document.getElementById('ifon').onclick = function(){ var getval = Checkbox(this.form); if (getval == 'on') { document.getElementById("data").submit(); } else { alert(getval); } } And here is my HTML for the form in question: <form id="data" name="data" %}"> <input type='hidden' name='status' value="Delete"> </form> I'm new to Javascript so maybe I'm missing something. This is a checkbox and Javascript seems to know what the value is based on my testing. I just can't seem to get the form to submit. Thanks for the help in advance. -
Passing a Django object into javascript?
I have the following "object" within my views that I'm passing into my template via the context: def objects(request) events = Object.objects.filter(Q(when__gt=datetime.datetime.now().date())).order_by('-when') context = { 'events': events, } return render(request, "thinkingplace/events.html", context) I'm then attempting to use this for jQuery uses on the front end template: <script type="text/javascript"> var events = '{{ events }}'; console.log(events); </script> I've tried using template tags - but I receive the "object is not JSON serializable error" - I've tried all manner of things but nothing is work. Does anyone have any ideas?? -
Django rest framework serialize ArrayField as string
I have a field in my Model class with an 'ArrayField' and I want it to serialize back and forth as a string of values separated by comma. models.py from django.contrib.postgres.fields import ArrayField class Test(models.Model): colors = ArrayField(models.CharField(max_length=20), null=True, blank=True I followed this solution - https://stackoverflow.com/questions/47170009/drf-serialize-arrayfield-as-string#= But getting bellow error - TypeError: to_representation() takes 2 positional arguments but 3 were given Please help. -
Any IDE provide an environment for AngularJS4(front-end) and DJango(back-end) development
I have searched a lot but could not find any satisfying answer. I want to know if any IDE provide environment for web development using Angular and DJango. please tell me. I will be thankful for your guidence. -
Is it possible to have a Heroku app I built be on the same domain as my Wordpress website?
I have a website hosted on Wordpress at domain [my domain name].com. I built an app using Django that is currently deployed on Heroku at [my domain name].herokuapp.com. The apps do not have conflicting routes. For example, the '/' route does not exist on the app I built myself. Is it possible to configure my DNS settings on Heroku such that I can use my custom domain name where a Wordpress website already lives? -
how to filter Django objects with a varying number of filter terms
Users can search for articles in my database with a set of terms. For example, "police body camera force". I then want to return to the user a list of articles where the title or source of the article contains ANY one of the terms the user entered. I'm not sure how to do this, especially since I don't know how many words there will be in the user's query. I thought the code would be something like this: user_query = "police body camera force" user_query_term_list = user_query.split(' ') for term in user_query_term_list: results = Article.objects.filter(Q(title__icontains="term")|Q(source__icontains="term")) ...and then somehow combine each of the results together in one queryset. If this is the most efficient approach, how do I combine the results from each of the loops into one queryset? And if there is a better way of accomplishing my goal, I would be grateful for the advice. Thank you. -
How can I force django to restart a database connection from the shell?
I have a django project on a Digital Ocean server. From my local machine, I connect to the database through ssh: ssh -L 63333:localhost:5432 me@my.server And change my local settings.py as: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 63333 } } And on a Jupyter QtConsole on my local machine, I follow these steps for setup: import os import django os.chdir('/path/to/my/project') os.environ['DJANGO_SETTINGS_MODULE'] = 'my_project.settings' django.setup() It all works fine until my ssh connection is broken by some reason. First I get this error (on a line that queries the database, say, my_model.objects.first()): DatabaseErrorTraceback (most recent call last) /home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args) 84 else: ---> 85 return self.cursor.execute(sql, params) 86 DatabaseError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. When I reconnect through ssh, I keep getting the following error: InterfaceErrorTraceback (most recent call last) /home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/base/base.py in _cursor(self, name) 233 with self.wrap_database_errors: --> 234 return self._prepare_cursor(self.create_cursor(name)) 235 /home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/postgresql/base.py in create_cursor(self, name) 211 else: --> 212 cursor = self.connection.cursor() 213 cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None InterfaceError: connection already closed The error only goes away if I restart the IPython … -
Django Query set is empty on chosen.js multiselect... Why?
I'm going to simplify my problem by focusing on one example I have the following javascript that determines which chosen multiselect option will be shown based on another select option. Everything is working correctly with the JS. For my problem i'm only going to show the group option selected. $(document).ready(function () { $('#accesslevelid').change(function () { $this = $(this) $('.content_box').each(function () { $select = $('select', this); if ($select.data('id') == $this.val()) { $(this).show(); $select.show().chosen(); } else { $(this).hide(); $('select', this).hide(); } }); }); }); Inside my form I have the following: {% block extra_js %} {{ block.super }} {{ form.media }} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.js" type="text/javascript"></script> <script src= "{% static '/accounts/chosen.jquery.js' %}" type="text/javascript"></script> <link rel="stylesheet" href="{% static '/accounts/chosen.css' %}"> <div id = "div_groupdimselect" class="content_box"> <select data-placeholder="Choose a group..." data-id="4" class="chosen-select" multiple tabindex="4" id = "id_groupdimselect" value = "{{facility.blevel}}" style="width: 1110px"> {% for facility in facilitydim %} <option value="{{facility.group_name}}">{{facility.group_name}}</option> {% endfor %} </select> </div> With my view I'm attempting to access the users chosen selection with the following, the datareducecode works when i filter on the users coid, but when i try datareducecode1 it returns and empty set: grouplist = request.POST.getlist('blevel') if request.method == 'POST' and selectedaccesslevel == '4': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid).values_list('blevel', flat … -
post request method equals ''options" in Django
I have posted a file from host machine to virtual machine which drjango restfull service running, I need to upload the file via this method def upload_file(request): if request.method == 'POST': # request.method = 'OPTIONS' form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'upload.html', {'form': form}) but request method equals to 'OPTIONS', I Searched on net and understood its about cros but I need exact guide to handle this issue. -
Django data leak between 2 separated tests
In my whole tests base, I experience a weird behaviour with two tests. They are completely isolated. However, I can find data from the first test in the second one. Here are the tests: file1 (services.tests) class ServiceTestCase(TestCase): @patch('categories.models.ArticlesByCategory.objects.has_dish_type') def test_build_dishtype_conflicts(self, mock_has_dish_type): # WARN: create interference in tests restaurant = RestaurantFactory() dt_1 = DishTypeFactory(restaurant=restaurant) cat_1 = CategoryFactory(restaurant=restaurant) art_1 = ArticleFactory(name='fooA1', restaurant=restaurant) art_2 = ArticleFactory(name='fooA2', restaurant=restaurant) abc_1 = ArticlesByCategory.objects.create(category=cat_1, article=art_1, is_permanent=True, dish_type=dt_1) abc_2 = ArticlesByCategory.objects.create(category=cat_1, article=art_2, is_permanent=True, dish_type=dt_1) mock_has_dish_type.return_value = [abc_1, abc_2] abcs_to_check = ArticlesByCategory.objects.filter(pk__in=[abc_1.pk, abc_2.pk]) conflicts = ServiceFactory()._build_dishtype_conflicts(abcs_to_check) self.assertDictEqual(conflicts, {dt_1.pk: 2}) file2 (products.tests) class ArticleQuerySetTestCase(TestCase): def test_queryset_usable_for_category(self): restaurant = RestaurantFactory() category_1 = CategoryFactory(name='fooB1', restaurant=restaurant) category_2 = CategoryFactory(name='fooB2', restaurant=restaurant) article_1 = ArticleFactory(restaurant=restaurant) article_2 = ArticleFactory(restaurant=restaurant) ArticlesByCategory.objects.create(article=article_1, category=category_1, is_permanent=True) queryset_1 = Article.objects.usable_for_category(category_1) # This line is used for debug for art in Article.objects.all(): print(art.name) When running test_build_dishtype_conflicts THEN test_queryset_usable_for_category in the same command, here are the results of the print in the second test: fooA1 fooA2 fooB1 fooB2 I suspect I did something wrong but can't find what.