Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
browser api by email in Model ViewSet django rest framework
in my django custom User model i set email as Username field and as primary key email = models.EmailField(_('email address'), max_length=255, unique=True, db_index=True, primary_key = True) USERNAME_FIELD = 'email' also i have created views for that model class UserView(viewsets.ModelViewSet): queryset = EmailUser.objects.all() serializer_class = EmailUserSerializer and set the url in my router router.register(r'users',UserView, base_name = 'utenti') question is: how can i access a single user providing his pk (the id, his email actually)? I've tried with localhost:8000/api/users/admin@mail.it/ but server ans: { "detail": "Not found." } i know the pattern should be this, because it works when there are numeric ids instead of email as primary key, and i can access with localhost:8000/api/users/1/. thank you for your time -
How to get datepicker to work in Django forms
I'm trying to get datepicker to work in my form in Django, but for some reason it's not working. I have jquery in my base template. #forms.py class ScheduleForm(forms.ModelForm): start_date = forms.DateField(widget=forms.DateInput(attrs={'class':'datepicker'}), initial=datetime.date.today, label="Start Date") # insert other fields here class Meta: model = Schedules fields = ('course_name', 'location', 'room', 'start_date', 'start_time', 'end_time', 'instructor', 'total_hours', 'hours_per_class', 'frequency', 'status', 'interval',) #start_one_schedule.html {% block main_content %} <script> $(function() { $('.datepicker').datepicker({ format: 'yyyy-mm-dd' }); }); </script> <h2>Initial Course Schedule</h2> <br> <form id="schedule_form" method="post" action="/schedule/start_one_schedule/"> {% csrf_token %} {{ form.errors }} {% for field in form %} <table class="init_sched_form"> <tr class="init_sched_row"> <td class="init_sched_label">{{ field.label_tag }}</td> <td class="init_sched_field">{{ field }}</td> </tr> </table> {% endfor %} <button type="submit" name="submit">Initial Schedule</button> <button type="submit" name="submit">Preview Schedule</button> </form> {% endblock %} I have no idea what I'm doing wrong, because I've checked this with other answers. Do I need to do something in another module? -
How do I enable stemming for my elasticsearch backend in django-haystack?
I'm trying to utilize Elasticsearch's stemming feature within haystack so that a query like lunch menus will return matches for objects that contain lunch menu. Here's my models.py and SearchIndex for my Menu model: models.py class Menu(models.Model): description = models.CharField(max_length=255) search_indexes.py from .models import Menu class MenuIndex(indexes.SearchIndex, indexes.Indexable): description = indexes.CharField(model_attr='description') def get_model(self): return Menu templates/my_app/menu_text.txt {{ object.description }} Here's the contents of my Menu table: +---+-------------------------------------------------------------------+ | 1 | Lunch Menu for 6-8 middle schools | +---+-------------------------------------------------------------------+ | 2 | Lunch Menu for 9-12 high schools | +---+-------------------------------------------------------------------+ | 3 | Lunch Menu for boundary schools | +---+-------------------------------------------------------------------+ | 4 | Lunch Menu for K-5 Elementary Schools | +---+-------------------------------------------------------------------+ If I search for lunch menu, I get results for all four of the above records. However, if I search for lunch menus, I don't get any results. How do I enable stemming for my description field so that a query of lunch menus returns results for all four of the above records? -
Django app action field in form tag
What is the difference between naming attribute action like action="/template/" and action="template/" in form tag. When i used the latter one, my submit buyyon stopped working. -
Can Django REST Framework serializers be used for other web-frameworks?
I want to use JSON serilization in mybaiohttp.web application. But I haven't found any libraries for that task in aiohttp universe. If there are any problem to use serilizers from django-rest-ramework with aiohttp? -
null value in column "name" violates not-null constraint when adding new item in django admin
I have added a new model to my admin, having in models.py: class EngineeringToolAttributeType(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=255, blank=True, null=True) api_url = models.CharField(max_length=255, blank=True, null=True) api_field = models.CharField(max_length=50, blank=True, null=True) active = models.BooleanField(default=True) def __str__(self): return self.name and the admin.py from extras.models import EngineeringToolAttributeType from django.contrib import admin class EngineeringToolAttributeTypeAdmin(admin.ModelAdmin): fields = ['name', 'description', 'api_url', 'api_field', 'active'] list_display = ('name', 'description', 'api_url', 'api_field', 'active') admin.site.register(EngineeringToolAttributeType, EngineeringToolAttributeTypeAdmin) but when trying to add (click on add button) via the admin, I get this: Internal Server Error: /website/admin/extras/engineeringtoolattributetype/add/ IntegrityError at /admin/extras/engineeringtoolattributetype/add/ null value in column "name" violates not-null constraint It never happened before. I know name is a "not null" field, but I'm still adding a record. How is that possible? -
How to annotate Django QuerySet with other object using Subquery
In Django version 1.11, Subquery expressions were added. I was hoping to use this feature to select a related model object based on some filters. This is an example from the documentation: from django.db.models import OuterRef, Subquery newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at') Post.objects.annotate(newest_commenter_email=Subquery(newest.values('email')[:1])) I would like to do the same, but instead of just annotating with the "newest_commenter_email" in this scenario, I'd like the whole newest_commenter object, like so: from django.db.models import OuterRef, Subquery newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at') Post.objects.annotate(newest_commenter=Subquery(newest[:1])) However, this results in the following error: FieldError: Expression contains mixed types. You must set output_field Is there a way around this? -
Merge unknown amount of querysets in django
What I want to accomplish is merge an unknown amount of querysets in the admin. I have a list with the authors a user can view and depending on the authors a user has in the list, he should be capable of seeing only their articles. What I have is: def get_queryset(self, request): #getting all the lists and doing not important stuff return (qs.filter(author = list(list_of_authors)[0]) | qs.filter(author = list(list_of_authors)[len(list_of_authors)-1])).distinct() This works if the user can view articles from two authors, however, for three it does not work. I tried using: for index in list_of_authors: return qs.filter(author = list(list_of_authors)[index]) Sadly I got only the last queryset. Is it even possible to merge querysets when the amount is unknown, because after a decent amount of searching I did not end up finding anything. -
Angular 2/4 authentication in Django - request stops at OPTIONS
I'm trying to connect Angular 2/4 application with my backend made with Django REST Framework. I'm using django-rest-framework-jwt module on backend with default settings and angular2-jwt on front. When i'm trying to log in, usually Angular send OPTIONS request, then POST with credentials included. Problem is, that POST didn't execute after receiving OPTIONS headers. I'm not sure is that back or frontend fault. I did few REST APIs in past with PHP and i never had anything in OPTIONS response body, in Django i have following: HTTP/1.0 200 OK Allow: POST, OPTIONS Content-Length: 504 Content-Type: application/json Date: Tue, 27 Jun 2017 14:24:34 GMT Server: WSGIServer/0.2 CPython/3.5.2 Vary: Accept X-Frame-Options: SAMEORIGIN { "actions": { "POST": { "password": { "label": "Password", "read_only": false, "required": true, "type": "string" }, "username": { "label": "Username", "read_only": false, "required": true, "type": "string" } } }, "description": "API View that receives a POST with a user's username and password.\n\nReturns a JSON Web Token that can be used for authenticated requests.", "name": "Obtain Json Web Token", "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "renders": [ "application/json", "text/html" ] } Can i override this response body, that is generated by JWT built-in views? I didn't modify anything in JWT module. … -
How to access postgres database on host from within docker container?
I have a docker-compose file with django project that trying to use database situated on host machine. Now my Dockerfile is: FROM python:3-slim ENV PYTHONUNBUFFERED 1 RUN mkdir /code. WORKDIR /code ADD . /code/ RUN pip install -r requirements.txt RUN export dockerhost=$(docker-machine ip) docker-compose.yml: version: "2" networks: workernetwork: webnetwork: services: static: volumes: - /static:/static - /media:/media image: alpine:latest web: build: . command: bash -c "SECRET_KEY=temp_value python /code/manage.py collectstatic --noinput && python /code/manage.py migrate && /code/run_gunicorn.sh" volumes: - .:/code volumes_from: - static env_file: - secrets.env ports: - 443:443 networks: - webnetwork extra_hosts: - "dockerhost:${dockerhost}" DATABASES in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'revolution', 'USER': get_env_setting('POSTGRES_USER'), 'PASSWORD': get_env_setting('POSTGRES_PASSWORD'), 'HOST': 'dockerhost', 'PORT': 5432, } } What Im doing wrong? Thx for attention! -
Django - placing and accessing a js file in root directory
I am trying to implement Firebase cloud messaging push notifications in my Django project. Firebase would look for a js file named firebase-messaging-sw.js in a project' root directory (no matter, what sort of project it is). So, the problem is that I can't figure out what is my project's root directory (sorry, for being stupid), and how to make Firebase see this file. Just as an experiment, I copy-pasted the js file to each and every folder of my project, and still no success (Firebase service can't see the file). Here's my settings.py file (with relevant content): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT_URLCONF = 'android_blend.urls' WSGI_APPLICATION = 'android_blend.wsgi.application' PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) STATIC_URL = '/static/' if DEBUG: MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","static-only") #STATIC_ROOT = [os.path.join(BASE_DIR,"static-only")] MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","media") #MEDIA_ROOT = [os.path.join(BASE_DIR,"media")] STATICFILES_DIRS = ( #os.path.join(os.path.dirname(BASE_DIR),"static","static"), os.path.join(BASE_DIR,"static"), ) My Django project layout is like this: android_blend android_blend settings.py url.py wsgi.py app1 app2 ... appN manage.py So the question is, what should I do in order for an outside service app (Google Firebase) be able to see the javascript file ? -
How to load webpack bundle which has content based hash filename as static file in Django?
I am using create-react-app to create a front end for a django based application. How would I import the js bundle generated by create-react-app in a Django template. The bundle filename is in the following format. main.3cf06d58.js The issue is that every time I rebuild the bundle the hash based on the contents in the filename changes. This in turn breaks my static file import in my Django template <script type='text/javascript' src='{% static 'js/bundle/main.c86ade78.js' %}'></script> Is there a way of setting custom Webpack bundle filenames in create-react-app? This setting doesn't seem to be available as I have not ejected and therefore do not have access to the Webpack configuration file. -
Save related Images Django REST Framework
I have this basic model layout: class Listing(models.Model): name = models.TextField() class ListingImage(models.Model): listing = models.ForeignKey(Listing, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to=listing_image_path) Im trying to write a serializer which lets me add an rest api endpoint for creating Listings including images. My idea would be this: class ListingImageSerializer(serializers.ModelSerializer): class Meta: model = ListingImage fields = ('image',) class ListingSerializer(serializers.ModelSerializer): images = ListingImageSerializer(many=True) class Meta: model = Listing fields = ('name', 'images') def create(self, validated_data): images_data = validated_data.pop('images') listing = Listing.objects.create(**validated_data) for image_data in images_data: ListingImage.objects.create(listing=listing, **image_data) return listing My Problems are: I'm not sure how and if I can send a list of images in a nested dictionary using a multipart POST request. If I just post an images list and try to convert it from a list to a list of dictionaries before calling the serializer, I get weird OS errors when parsing the actual image. for key, item in request.data.items(): if key.startswith('images'): # images.append({'image': item}) request.data[key] = {'image': item} My request code looks like this: import requests from requests_toolbelt.multipart.encoder import MultipartEncoder api_token = 'xxxx' images_data = MultipartEncoder( fields={ 'name': 'test', 'images[0]': (open('lilo.png', 'rb'), 'image/png'), 'images[1]': (open('panda.jpg', 'rb'), 'image/jpeg') } ) response = requests.post('http://127.0.0.1:8000/api/listings/', data=images_data, headers={ 'Content-Type': images_data.content_type, 'Authorization': 'Token' + … -
How to properly setup systemctl service with gunicorn?
I have a Django project that I run with gunicorn. My manage.py file is in /home/Projects/myproject/myproject. My virtualenv is in /home/myproject. In /lib/systemd/system I created a myproject.service file: [Unit] Description=My Project After=network.target [Service] User=my_user Group=my_group WorkingDirectory=/home/Projects/myproject/myproject ExecStart= ??? ExecReload=/bin/kill -HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID Restart=on-failure [Install] WantedBy=multi-user.target I want to know how to properly configure my service file so that it can run my gunicorn start server command on server restart, failure, etc. -
Django forward url parametr to ListView
How can i get url parametr and filter by queryset ListView ? Can you write mi example ? regards Dominik -
Django 1.11 ignoring tempate trans tag
I've set up everything right, and when I launch: makemessages --locale fr --locale en it only takes in account the translation string used in the Python files, not in the template files (NB: I have {% load i18n %} in the first line of all the template files). What did I forget? """ Django settings for cocktails project. Generated by 'django-admin startproject' using Django 1.11.2. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'd!q-teup0+1fca*(x)r2nuvvdppj+l-w_$iyjhifp)$_*^8yh8' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app.apps.AppConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'cocktails.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'cocktails.wsgi.application' # Database … -
Django Error when trying to post to endpoint of unmanaged model
I'm using Django Rest framework, and trying to create an endpoint for creating some object, which doesn't suppose to be saved in DB (managed=false). I want to get 'JSONApi' response, so I understood I should create a model and a serializer for it. This is the classView: class OssObjectsViewSet(AuthenticatedCreateModelMixin, GenericViewSet): serializer_class = OssObjectSerializer def get_queryset(self): m = OssObject() return [m] this is the model: class OssObject(models.Model): class Meta: managed = False class JSONAPIMeta: resource_name = "oss_objects" id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True, unique=True, primary_key=True) @property def urn(self): return 'yyy' That's the serializer: class OssObjectSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = OssObject fields = ['id', 'urn'] When sending Post request to the endpoint, I'm getting {"data": {}, "message": "('relation \"submittals_ossobject\" does not exist\\nLINE 1: INSERT INTO \"submittals_ossobject\" (\"id\") VALUES (\\'81400b5b-...\\n ^\\n',)", "error_id": "8b9a3352-da41-4dd3-be09-5e63602aef46", "code": 10001} When creating the classView with 'AuthenticatedListModelMixin' and send 'Get' request- it works fine. -
Passing data between views in Django
I have a FormView (currently a WizardView as I have multiple forms) which takes input from the (anonymous) user and passes the cleaned data to be used in a request to an external api. However I'm not clear how best to pass the data recieved from one view to the next view? The data received from the api is to be displayed in the next view. (If the data was held internally (rather than in an external api) I would probably try a ListView with the relevant parameters passed from the FormView to the ListView via a session) However the api returned data will have many pages of data. What's the best way to manage this in django? (This doesn't need to be async as the returned data is required before the user can proceed.) class QuotesWizard(SessionWizardView): def get_template_names(self): return [QUOTES_TEMPLATES[self.steps.current]] def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): return redirect(settings.LOGIN_REDIRECT_URL) return super().dispatch(request, *args, **kwargs) def done(self, form_list, form_dict, **kwargs): postcode = form_dict['postcode'].cleaned_data['postcode'] service = form_dict['service'].cleaned_data['service'] usage = form_dict['usage'].cleaned_data['usage'] usage = convert_usage(usage) # get data from external api data = get_quotes(postcode, usage_ofgem, service_type) # redirect to quotes page - how to manage transfer of data? return redirect('quotes') -
Remove objects after update_index with django haystack
I have two models Notice and SolrIndex for objects to add index. class SolrIndex(models.Model): id = models.AutoField(primary_key=True) object_id = models.IntegerField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey('content_type', 'object_id') date_created = models.DateTimeField(auto_now_add=True) In Haystack search_indexes.py: class NoticeIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) id = indexes.IntegerField(model_attr='id') title = indexes.CharField(model_attr='title') description = indexes.CharField(model_attr='description') date_pub = indexes.DateTimeField(model_attr='date_pub') def get_model(self): return Notice def index_queryset(self, using=None): """Used when the entire index for model is updated.""" content_type = ContentType.objects.get_for_model(Notice) solr_indexes = SolrIndex.objects.filter(content_type=content_type).values_list('object_id', flat=True) notices = self.get_model().objects.filter(id__in=solr_indexes) return notices I want remove objects from database (variable: solr_indexes) after indexing to Solr. how to do it? -
Django filter queryset to find lowest price of product or preferred merchant price if prices are the same
I have the following in models.py: class Merchant(models.Model): name = models.CharField(max_length=256) priority = models.PositiveIntegerField() class MerchantWine(models.Model): merchant = models.ForeignKey("Merchant") wine_vintage = models.ForeignKey("WineVintage") price = models.DecimalField(null=True, blank=True, max_digits=8, decimal_places=2) minimum_purchase_unit = models.PositiveIntegerField() Question: In my queryset I'm trying to restrict the MerchantWine objects to A. the lowest price version where there are duplicate WineVintages and B. if prices are the same then Id like to select the price corresponding to the Merchant with the lowest priority. In my views.py I tried the following: def get_queryset(self): #A Restrict MerchantWines to lowest price version(s) of same wine_vintage minimum_prices = MerchantWine.objects.values('wine_vintage').annotate(lowest_price=Min('price')) results_list = MerchantWine.objects.filter(price__in=minimum_prices.values('lowest_price')) #B Restrict MerchantWines to preferred merchant of same wine_vintage and price preferred_merchants = results_list.values('wine_vintage').annotate(lowest_priority=Min('merchant__priority')) results_list = results_list.filter(merchant__priority__in=preferred_merchants.values('lowest_priority')) # NOT WORKING ON PROD: Chardonnay return results_list It seems that A.) is working but B.) does not always work. Can anyone help? Many thanks in advance. -
Inline create/edit functionality like in Django's admin site
I want to implement an inline create/edit functionality like in Django's admin site. (see picture below) This is what I got so far: For dynamically adding and removing the form, I use django-dynamic-formset jquery plugin. Any suggestions or ideas on how to implement this? Thanks! -
Import Error:No module named app.management.commands
when I run the command to import my python file, i am getting import error saying no modue named app.management.commands. >>> from app.management.commands import scripty Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: No module named app.management.commands Can anyone please help me. -
Access input field created dynamically in Handlebars template
I have a Handlebars template in which I create a checkbox: {% verbatim myblock %} <script id="example_template" type="x-tmpl-mustache"> {{#each loaded_texts}} <input type="checkbox" name="include_{{this.[1]}}"> {{/each}} </script> {% endverbatim myblock %} This is then rendered like this var source = $('#example_template').html(); var template = Handlebars.compile(source); var rendered = template(data); $('#example').html(rendered); And put in some span like <span id="example"></span> I then want to access the values of these checkboxes with javascript to create a query string which I'll use to retrieve json data from Django, like this: function getQueryStr() { var queryStrParts = []; $('#example input').map(function() { if ($( this ).is(':checked')) { queryStrParts.push($( this ).attr('data-label') + "=" + $( this ).attr('data-value')); } }); return queryStrParts; } But I can't access these checkboxes. If I manually create the checkboxes in my span, it works fine. What can I do to solve this? Is this even the most reasonable way to achieve this? -
AttributeError - Namespace object has no attribute username
Hi am new to python and tried to run below script and getting attribute error. #!/usr/bin/python import json import sys import argparse try: import requests except ImportError: print "Please install the python-requests module." sys.exit(-1) def get_json(location, devincuser, password): # Performs a GET using the passed URL location location += "?per_page=10000" r = requests.get(location, auth=(devincuser, password),verify=False) return r.json() def main(): parser = argparse.ArgumentParser(description="Satellite Errata Reporter") # Arguments parser.add_argument("-u", "--devincuser", type=str.lower, help="Username to access Satellite", action="store", default='devincuser') parser.add_argument("-p", "--password", type=str, help="Password to access Satellite", action="store", default='password') parser.add_argument("-n", "--localhost", type=str.lower, help="Satellite server (default: localhost)", default='localhost') parser.add_argument("-o", "--organization", type=str.lower, nargs="*", help="Filter on this space-delimited list of organization(s)", default='') parser.add_argument("-e", "--environment", type=str.lower, nargs="*", help="Filter on this space-delimited list of lifecycle environments", default='') parser.add_argument("-c", "--collection", type=str.lower, nargs="*", help="Filter on and group by this space-delimited list of host collections", default='') parser.add_argument("-t", "--type", type=str.lower, nargs="*", help="Filter on this space-delimeted list of errata types (bugfix, enhancement, and/or security)", default='') parser.add_argument("-s", "--severity", type=str.lower, nargs="*", help="Filter on this space-delimited list of severities (critical, important, moderate, low)", default='') args = parser.parse_args() # Check username and password if not (args.username and args.password): print "No complete account information provided, exiting" exit (-1) # set up api url sat_api = "http://%s/172.17.12.129/api/v2/" % args.server katello_api = … -
can't access validated data or FK relationship within serializer's create() method
I can't seem to access a foreign key value within a serializer's create method. On submitting a POST to create a new instance I receive the following error: DoesNotExist at /api/v1/organisation/provider/ Service matching query does not exist. within the traceback is the following: File "/code/classification/serializers.py" in create 114. thisService = Service.objects.get(name=validated_data.get('service')) the POST data is as follows: {service: "ServiceProvider1", tenantIdentifier: "9f0e40fe-3d6d-4172-9015-4298684a9ad2", enabled: true} My question: How can I successfully reference a Service instance based on its name field (not its PK) from the ConnectedService model (FK relationship) models.py: class Service(models.Model): name = models.CharField('provider name', max_length = 32) displayName = models.CharField('provider label display name', max_length = 32) helpText = models.TextField('Explanatory text about this provider', max_length = 140, blank=True) authzUrl = models.URLField('authorisation URL for service', max_length = 512, blank=True, null=True) appID = models.CharField('ID for this app as provided by cloud provider', max_length = 64, blank=True, null=True) def __str__(self): return self.displayName class ConnectedService(models.Model): service = models.ForeignKey(Service, related_name='connected') tenantIdentifier = models.CharField('Tenant identifer for organisation', max_length = 128, null=True, blank=True) enabled = models.BooleanField(default=True) organisation = models.ForeignKey('Organisation', blank=True, null=True) #string reference used as a lazy reference for Organisation serializers.py: class ConnectedServiceSerializer(serializers.ModelSerializer): services = ServiceSerializer(many=True, required=False) class Meta: model = ConnectedService fields = ('tenantIdentifier', 'enabled', 'services', 'organisation' …