Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Interaction with not User's Instance
I have models Company and Pricelist. Company have a ManyToMany field subscribed_companies. Idea is that Company A can subscribe Company B and after that Company B may transfer pricelist to Company A. So Pricelist have a ManyToMany field transfered_to. What is the best practice to let Company A delete or make inactive transfered pricelist in view of there are other Companies use? Is it good enough to let Company A edit transfered_to field? Thanks! -
What's the propper way to filter the kwargs["queryset"] of a formfield_for_manytomany?
I'm trying to filter the list shown in a ManyToMany field using a formfield_for_manytomany (on my CMSPluginBase-inheriting plugin). The relation works like this: MyPluginA is used in Pages with template templetaA.html, of which I want to show only the draft versions in the picker (to avoid duplicate entries), so I did this: ... draft_a_pages = filter(lambda p: p.template == 'templetaA.html' and not p.publisher_is_draft, Page.objects.all()) unpublished_as = [placeholder.get_plugins_list(lang)[0] for placeholder in [page.get_placeholders()[0] for page in draft_a_pages]] kwargs["queryset"] = unpublished_as ... However the code throws an error further down because unpublished_as is a list and not a queryset (it doesn't have an all method). I've been looking at some answers and thought of doing something like this, getting rid of unpublished_as: ... kwargs["queryset"] = MyAPlugin.objects.filter(page__in=draft_a_pages) ... However it doesn't seem that one can filter Plugins like that. I've settled for doing it with pk, like so: ... draft_a_pages = filter(lambda p: p.template == 'templetaA.html' and not p.publisher_is_draft, Page.objects.all()) unpublished_as_ids = [placeholder.get_plugins_list(lang)[0].pk for placeholder in [page.get_placeholders()[0] for page in draft_a_pages]] kwargs["queryset"] = MyAPlugin.objects.filter(pk__in=unpublished_as_ids) ... But there's got to be a better way to pull this off, right? -
Use function or template rather than a URLconf file in Django
So I have a number of projects defined in my database, with domains, views, templates and their ordering set as fields. I am using django-host to select the relevant URLconf file according to the domain name. Using the latest Django version, v2.1. hosts.py from django_hosts import patterns, host from custom.models import Project projects = Project.objects.all() host_patterns = patterns( '', *[ host(r'^{}$'.format(project.domain), '{}.urls.py'.format(project.domain), project.domain) for project in projects ] ) Rather than having to define and create a urls.py for each project domain name, I'd like to either provide a function that returns urlpatterns, or perhaps a template file that substitutes the appropriate values according to the determined domain name. Although I would like this to result in urls.py being created dynamically, it only needs to be at startup, not necessarily per request. Is this supported at all Django, and if not, would it be feasible by writing custom startup code and/or middleware? urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ # Admin part: url(r'^admin/', admin.site.urls), ] # TODO: obtain relevant project from database for view in project.views: urlpatterns.extend([url(r'^{}$'.format(view.__name__), view, name=view.__name__)]) -
Change format for Duration field in django admin
I'm using django's DurationField in a model to calculate the time difference between two DateTimeField. On the admin side for that model, the field shows up like this: Cumulative Total time: 0:51:33 Or Cumulative Total time: 2 days, 3:10:21 Is it possible to change the format for this field to the below given format: Cumulative Total time: 2 days, 3 hours, 10 minutes, 21 seconds -
Django test taking 20min+
I have a mysterious test that's taking much longer to run than it should. I have tried to debug it for a while now but I've run out of creativity. The test does create a lot of database records, but still, it's only a few hundreds, I could understand it taking one minute, but definitely not 20. Here's the relevant code that chokes for some reason: from rest_framework.test import APITestCase class MyTest(APITestCase, ...): ... def setUp(self): self.setup_questions() def setup_questions(self): question_levels = [ QuestionLevelFactory.create(title="Major", ...), QuestionLevelFactory.create(title="Minor", ...), QuestionLevelFactory.create(title="Recommended", ...) ] questionnaire1 = QuestionnaireFactory.create(...) questionnaire2 = QuestionnaireFactory.create(...) possible_answer_set = PossibleAnswerSetFactory.create(...) for question_level in question_levels: if question_level.title == "Recommended": questionnaire = questionnaire2 counter = 25 else: questionnaire = questionnaire1 counter = 100 for i in range(counter): if i <= 97: question = QuestionFactory.create( level_object=question_level, possible_answer_set=possible_answer_set, questionnaire=questionnaire ) else: question = QuestionFactory.create( level_object=question_level, possible_answer_set=possible_answer_set, questionnaire=questionnaire, code="{}-{}".format(question_level.title, i) ) if i < 95: AnswerFactory.create( question=question, assessment=self.assessment, value="yes" ) elif i <= 97: AnswerFactory.create( question=question, assessment=self.assessment, value="not_applicable" ) else: AnswerFactory.create( question=question, assessment=self.assessment, value="no", justification="{} {} justification".format(question_level.title, i) ) Note that, when the question_levels are listed in this order, the test only starts chocking when processing the "Minor" level. The first one ("Major") one is processed much … -
Django gunmail send bulk email with one recipient when delivered
I am trying to send bulk email with Django Anymail app and Gunmail. The problem I am facing is that I am unable to send email without to. emails = ['user1 <user@example.com', 'user2 <user2@example.com'] msg = EmailMultiAlternatives( subject="Please activate your account", body="Click to activate your account: http://example.com/activate", from_email="Biorelevant <support@example.com>", bcc=emails, reply_to=["Helpdesk <support@example.com>"] ) msg.send() In that case i get: Mailgun API response 400: BAD REQUEST { "message": "'to' parameter is missing" } I want a user to see in his mail client that he is the only recipient of the email. I found this question but it does not solve my problem because a user then only sees one recipient and not his own. Can I achieve it in any other way than sending emails one by one? -
I can't access request in my Django template
Hello Awesome People! A simple question. I have this view: def hello(request): users_list = User.objects.all() context = {"users_list":users_list} return render_to_response('index/users-list.html',context=context) In my template, I want to access COOKIES, with request {% for u in users_list %} {% if u.id in request.COOKIES.room|split %} remove user {% endif %} {% endfor %} I tried displaying {{request.COOKIES}}, nothing shown. It seems that request isn't available in the template. split is a custom tag filter @register.filter def split(string_,sep=","): return string_.split(sep) Why I can't access the request?, and also none of my global variables available in my project/context_processors.py are accessible -
React-Rest app, where to fetch data from database
I have an App composed by back-end: Python with Django and Django REST, and front-end composed of React. Right now I have Excel files with data, which I import with python in json format to the back-end, so they are available for a fetch in the front-end via REST-url like here. I am now translating my data into a web-based-database to be queried into my app. But I have questions regarding the structure of my app with this change. I have url-based queries for my new database. Should I continue to import the queries in the back-end REST framework and, from there, to React? Or should I use the url-based queries directly inside my React, substituting the REST url calls? -
Python django admin: How can I show only items belonging to specific model in an admin page?
I'm learning django for building my website. I learned how to create models, views, but now I have somequestion relative to admi interface. So I have tis code: from django.db import models class AudioBook(models.Model): titolo=models.CharField(max_length=250) capitoli=models.ManyToManyField('Chapters') class Chapters(models.Model): capitolo=models.CharField(max_length=250) Now, when I add a new audiobook I can see chapters previously added to others audiobooks. This is bad. I want only the chapters taht belong to this audiobook, so, when I add a new one, the list must be empty. I tried some things: adding limit_choices_to = models.Q(audiobook__titolo=titolo), but it doesn't work. In command line I can retrieve these info by adding filters on Chapters object, but I can reproduce this situation in admin interface. Any idea? I searched on google but I didn't find anything that helps me. Germano -
Is there a beginner Django book that doesn't teach how to create blogs?
I want to learn how to create simple Django web apps with database like an inventory system or simple list filtering site. I'm getting a bit frustrated because all tutorials I see are all teaching me how to create blogs but I have no intention of creating blogs or social media sites. I'm a beginner and I want to learn how to create super basic web apps and not full-blown social media sites. I hope you can point me to a simple tutorial that tackles how to create simple apps that access database. Thanks in advance! -
Django dockerfile with alpine, shared libraries missing
I'm trying to create a dockerfile for my django server. Here is my dockerfile: FROM python:3.6-alpine3.7 # Copy in your requirements file ADD requirements-pip.txt /requirements-pip.txt RUN set -ex \ && apk add --no-cache --virtual .build-deps \ gcc \ make \ libc-dev \ musl-dev \ linux-headers \ pcre-dev \ libffi-dev \ jpeg-dev \ libxml2-dev \ libxslt-dev \ openblas-dev \ gfortran \ build-base \ freetype-dev \ libpng-dev \ llvm-dev \ postgresql-dev \ && python3.6 -m venv /venv \ && /venv/bin/pip install -U pip \ && LIBRARY_PATH=/lib:/usr/lib /bin/sh -c "/venv/bin/pip install --no-cache-dir -r /requirements-pip.txt" \ && runDeps="$(\ scanelf --needed --nobanner --recursive /venv \ | awk '{ gsub(/,/, "\nso:", $2 }' \ | sort -u \ | xargs -r apk info --installed \ | sort -u \ )" \ && apk add --virtual .python-rundeps $runDeps \ && apk del .build-deps # Copy your application code to the container (make sure you create a .dockerignore file if any large files or directories should be excluded) RUN mkdir /code/ WORKDIR /code/ ADD . /code/ # uWSGI will listen on this port EXPOSE 8000 # Add any custom, static environment variables needed by Django or your settings file here: ENV DJANGO_SETTINGS_MODULE=myapp.settings # uWSGI configuration (customize as needed): … -
Django how to pupulate database
I have some problem to populate my database. I tried to stick to the Django Tutorial but it doesn't work. I miss something but i don't know what :(. I have the following model: from django.db import models class QA_machine_DB(models.Model): QAmachine = models.CharField( max_length = 64) status = models.CharField(max_length=32) def __str__(self): return "%s %s" % (self.QAmachine, self.status) class Report(models.Model): store = models.CharField(max_length= 128) service = models.CharField(max_length= 128) user = models.CharField(max_length= 64) dump_date = models.CharField(max_length= 128) branch= models.CharField(max_length= 128) FK_report=models.ForeignKey(QA_machine_DB, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return "%s %s" % (self.store, self.user) The following code is to to populate the DB: def import_data_django(self): # import Data to Django remote_data= self.report.to_dict('index') current_machine = QA_machine_DB.objects.get_or_create( QAmachine =self.name, status = self.status,) for key in remote_data.keys(): Report.objects.get_or_create(service= remote_data[key]['service_name'], user=remote_data[key]['user'], store= remote_data[key]['shop'], dump_date=remote_data[key]['date'], branch = remote_data[key]['issues_key'], FK_report= current_machine) # I guess here is the problem print ( self.name, '-',self.status, 'in DB :)' ) if __name__ == '__main__': machines=['qa0668'] #machines=['qa0668','con-qa-1010','qa1313'] for elt in machines : machine=QA_machine_(elt) machine.fill_info_status() machine.find_state_QA_nmachine() machine.import_data_django() I got the error : TypeError: int() argument must be a string, a bytes-like object or a number, not 'QA_machine_DB' IF someone has a clue what I miss please... Thank you in advance. -
realtime with django web sockets
I have a question for you please, I have an app with django channels: THE FIRST QUESTION the idea is to get all transaction in real time, but the transaction is growing in each moment, example the app is beginning to 10 transactions and before is 100 transactions and more, the app realtime is a little slow, how to do the app to get transactions? maybe one by one transaction if I decided to do one by one, how to implement this function: my function to get all transaction is: class TransactionConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'transaction_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send the message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'list_transaction', 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) async def list_transaction(self, event): token = event['message'] message = self.list_trans_all(token) await self.send(text_data=json.dumps({ 'massage': message })) # HERE RETURN … -
Get List of related objects - Django Queryset
How do I use django's queryset to get a list of users from the MyUser table where transaction_paid is False in my UserBankTransaction table? class UserBankTransaction(models.Model): user = models.ForeignKey(MyUser) plaid_transaction_id = models.CharField(max_length=300, unique=True) charge_amount = models.DecimalField(max_digits=10, decimal_places=2) account_id = models.CharField(max_length=300) location_name = models.CharField(blank=True, max_length=300) roundup_amount = models.DecimalField(max_digits=10, decimal_places=2, null=True) transaction_date = models.DateField() transaction_paid = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now=False, auto_now_add=True) class MyUser(AbstractBaseUser): username = models.CharField(max_length=255,unique=True,) email = models.EmailField(verbose_name='email address',max_length=255,unique=True) first_name = models.CharField(max_length=120,null=True,blank=True,) last_name = models.CharField(max_length=120,null=True, blank=True,) created = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated = models.DateTimeField(auto_now=True, null=True, blank=True) -
Django LoginView with next parameter post gets error 400
I have modified Django authentication form to log in with an email and password: class UserLogInForm(forms.Form): email = forms.EmailField( label=_('Email'), widget=forms.EmailInput(attrs={'placeholder': '@', 'focus': True}), ) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, ) I have created a view with which I can log in just fine : 47 class LoginView(SuccessURLAllowedHostsMixin, AjaxTemplateMixin, FormView): 48 template_name = 'accounts/login_inner.html' 49 form_class = UserLogInForm 50 redirect_field_name = REDIRECT_FIELD_NAME 51 success_url = '/' 52 54 def get_success_url(self): 55 userid=self.get_form_kwargs()['request'].user.pk 56 user = User.objects.get(pk=userid) 57 return reverse('main',kwargs={ 'pk': userid}) 58 59 def get_form_kwargs(self): 60 kwargs = super().get_form_kwargs() 61 kwargs['request'] = self.request 62 return kwargs 63 64 def form_valid(self, form): 65 login(self.request, form.get_user()) 66 messages.add_message(self.request, messages.SUCCESS, 67 'Welcome.') 69 data = { 70 'success_url': self.get_success_url() 71 } 72 return JsonResponse(data) Now I am trying to make this work with Django auto redirection (when a user is disconnected and tries to access a page that requires to be logged in, it redirects to /accounts/login/?next=/page_that_requires_authentication/) So I added the following url : path('accounts/login/', auth_views.LoginView.as_view(template_name='accounts/login.html', authentication_form=UserLogInForm)), The page loads well when using method get and the form displays just like my custom page but when clicking on the submit button I get an error code 400: [09/Aug/2018 14:04:36] "POST /login/ HTTP/1.1" … -
Why doesen't css file apply on html file - Django
I have a problem that my .css file doesn't apply on my .html file in Django. But when I, for example, type . some class name from the .html file, pycharm offers me to finish the class name. So, I think its linked right. Anyway, I put in my settings file: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' Run python manage.py collectstatic succesfuly and added my .css file to .html with command: {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'base.css' %}"/> Inside of my project I have something like this: -website -static -admin (generated when I run the command above) -images -base.css -templates -navbar.html -base.html -app1 -app2 -etc For testing purpose I just put simple div in the head section of the .html file: <div class="example">jvhgbhjgf</div> And in .css file: .example { background-color: red; border-radius: 15px;} -
Django Rest Framework: POST object with id
Is it possible to POST a new object while also specifying its id instead of auto incrementing? This is a one time import and the database id sequence would be corrected afterward. class TestModelSerializer(serializers.ModelSerializer): class Meta: model = TestModel fields = ('id', 'name') class TestModelViewSet(viewsets.ModelViewSet): queryset = TestModel.objects.all() serializer_class = TestModelSerializer import requests def test_post(endpoint): data = { "id": 30, "name": "Test", } r = requests.post(endpoint, data=data) print(r.status_code, r.reason) test_post('http://localhost:8000/api/test_model/30/') >>> 405 Method Not Allowed test_post('http://localhost:8000/api/test_model/') >>> 201 Created 201 Created creates a new object but with the next id in sequence instead of the desired id. I've also tried r = requests.put('http://localhost:8000/api/test_model/30/', data=data) but get 404 Not Found -
Django: python manage.py runserver works, but python3 manage.py runserver doesn't work
Python 2 with Django 1.8 Python 3 with Django 2.1 I wanted to start fun with django on opensuse. The first problem what i have is server runs only on python2. I dont know what to do. Could anybody help me ? -
django admin action with additional input as raw_id_fields
I'm using django 2.1, in the admin I want to add an input data for an action and everything seems fine following this: https://www.agiliq.com/blog/2014/08/passing-parameters-to-django-admin-action/ Now, I want to change the widget of 'price' to became the same of the "raw_id_fields" how can this be done? The raw_id_fields works when editing the record, I need it in the changelist next the action list. class UpdateActionForm(ActionForm): price = forms.IntegerField() #price = forms.ModelChoiceField(queryset=MyOBj.objects.all(), empty_label="(None)",) # this works but load time of page is huge -
Django Rest Framework Serializer Doesn't Display ALL Fields
I have a problem where DRF isn't displaying all of my fields correctly for a model class / reference table (specifically the primary key). My Model Class looks like this (very simple): class UnitOfIssue(models.Model): code = models.CharField(max_length=2, primary_key=True) description = models.CharField(max_length=16) class Meta: ordering = ('code',) def __str__(self): return "{0} - {1}".format(self.code, self.description) My Serializer Looks like this: class UnitOfIssueSerializer(serializers.HyperlinkedModelSerializer): """ """ url = serializers.HyperlinkedIdentityField( read_only=True, view_name='unitofissue-detail', format='html', lookup_field='code') class Meta: model = UnitOfIssue fields = ('code', 'description', 'url') # fields = '__all__' And I'm using a generic view: class UnitOfIssueDetail(generics.RetrieveUpdateDestroyAPIView): queryset = UnitOfIssue.objects.all() serializer_class = UnitOfIssueSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) lookup_field = 'code' In order for the UnitOfIssue primary key code to be displayed in the auto-generated UI, I have to define fields = ('code', 'description', 'url') in the serializer instead of fields = '__all__'. I want to just be able to use the '__all__' syntax but I can't figure out what's going wrong. Also, I'm using Django==1.11.13 and djangorestframework==3.8.2 -
Django TypeError at /account/register/ 'tuple' object is not callable
Issue Description 1 -here i am trying to render two forms with their fields on a wizard. User fields and Profile fields (on a OneToOne relationship). the end game is to complete profile and User data on account signup. Now i have managed to achieve this which similar variations of the code in the views. the real issue lies with below 2- The images will not save to the database upon account creation. Please know i have done the following - set up media root options in the settings and main site urls -images also save to media room from the django admin, but i believe that functionality is specifically related to the models i have created my template is fairly large with the bootstrap elements included to i would not add it however it is set up to render specific fields from the two forms There is an error with my views My Views class RegisterView(CreateView): model = User, UserProfile form_class = RegistrationForm, UserProfileForm def post(self, request, *args, **kwargs): user_form = RegistrationForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_photo' in request.FILES: profile.profile_photo = request.FILES['profile_photo'] profile.save() registered … -
django-model-utils: how can I achieve a correct queryset._clone() with respect to subclasses?
I'm using the django-model-utils modul version 3.1.2 with django (2.0.8) and python 3.6. As a proxy for my real project consider following: models.py from django.db import models from model_utils.managers import InheritanceManager class ModelAManager(InheritanceManager): def get_queryset(self): return super(ModelAManager, self).get_queryset().select_subclasses() class ModelA(models.Model): name = models.CharField(max_length=100) objects = ModelAManager() def get_type(self): return self.__class__.__name__ def get_inherited_types(self): class_names = [inst.__name__ for inst in self._meta.get_parent_list()] class_names.append(self.__class__.__name__) return set(el for el in class_names) class ModelB(ModelA): amount = models.IntegerField() class ModelC(ModelB): value = models.DecimalField(max_digits=9, decimal_places=3) If I now create some instances and query these models, everything comes out as expected: ma = ModelA(name='Test1') ma.save() mb = ModelB(name='Test2',amount=2) mb.save() mc = ModelC(name='Test3',amount=3,value=3.0) mc.save() qs = ModelA.objects.all() qs <InheritanceQuerySet [<ModelA: ModelA object (10)>, <ModelB: ModelB object (11)>, <ModelC: ModelC object (12)>]> but if I _clone() this particular queryset, than the inheritance information (ModelB, ModelC) disappears: qs_c = qs._clone() qs_c <InheritanceQuerySet [<ModelA: ModelA object (10)>, <ModelA: ModelA object (11)>, <ModelA: ModelA object (12)>]> In my real project the _clone() method is called from the get_result(self, request) function in django.contrib.admin.views.main.py in line 187 and this is called during the process for displaying the get_type() method in my ModelA at the django admin site. This leads to incorrect "type" representation (expected values for … -
Django rest ordering for m2m fields
class Level(models.Model): name = models.CharField(max_length=100) class Position(models.Model): name = models.CharField(max_length=100) class PositionLevel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="position_levels") position = models.ForeignKey(Position) level = models.ForeignKey(Level) created_on = models.DateTimeField(auto_now_add=True) I have User which can have many position_levels. I am making filtering and ordering in django rest by each field. My problem is that I can't make ordering for last position name from position_levels__position__name queryset = get_user_model().objects.filter( account_type=models.User.ACCOUNT_TYPE_CHOICES[0][0]).\ annotate( last_position=F('position_levels__position__name') ) Value for last_position is first taken value from 3 possible in position_levels. How can order in annotate to order by position_levels__create_on value an to take object with last date. My intention is to use that value in url ordering: localhost:8000/api/users?ordering=-last_position And to sort users by their position or level. I have tried with adding property in user model, but it fails with ordering from url. I tried with manipulation with queryset but it in every scenario avoid to oder by that field. I tried with SQLraw but there doesn't work too. I am using django 1.10.8 -
Paginator in django
Hi i looking at https://docs.djangoproject.com/en/2.1/topics/pagination/ documentation about django paginator in the code it use from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.shortcuts import render def listing(request): contact_list = Contacts.objects.all() paginator = Paginator(contact_list, 25) # Show 25 contacts per page page = request.GET.get('page') contacts = paginator.get_page(page) return render(request, 'list.html', {'contacts': contacts}) And in template it use <div class="pagination"> <span class="step-links"> {% if contacts.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ contacts.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}. </span> {% if contacts.has_next %} <a href="?page={{ contacts.next_page_number }}">next</a> <a href="?page={{ contacts.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> I understand all the codes except in first time render what will be value of page In the line page = request.GET.get('page') i know django run ?page=Value and pass value to page argumant but what was the value of page in first render -
Django - How to check if model instance has unique one-to-many and many-to-many relations
Question I have five models: class Features(models.Model): name = models.CharField(max_length=100, unique=True) class Filter(models.Model): name = models.CharField(max_length=100, unique=True) class Model(models.Model): name = models.CharField(max_length=200, unique=True) class TrainSet(models.Model): name = models.TextField(unique=True) class Algorithm(models.Model): feature = models.ManyToManyField(Features) filter = models.ManyToManyField(Filter) model = models.ForeignKey(Model, on_delete=models.DO_NOTHING, null=True) train_set = models.ForeignKey(TrainSet, on_delete=models.DO_NOTHING, null=True) I am doing some measurements that produce a calculated prediction based on features, filters, model and trainset. Those together form an algorithm First four are being changed trough the development process and because of that I would like to save each measurement with algorithm version. Problem If I would not care for data redundancy and database table normalizations I could create a different yet same algorithm for measurements. But because i care for redundancy and normalization I would like to check if the algorithm with respective one-to-many and many-to-many already exists. If instance exists, use that instance, otherwise create a new one. after each measurement the server that calculates the result sends a JSON to my django server in following form: { "filters": ["filter1", "filter2"], "model": "model-1", "features":["feature1", "feature2"], "trainset": "trainset1" } The problem is that i cannot find a way to check if an algorithm already exists with all its relations. What is …