Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest - Use @action with custom decorator
I have a Rest API in Django and I have the following method in a class that extends ModelViewSet: @custom_decorator @action(methods=['get'], detail=False, url_name="byname", url_path="byname") def get_by_name(self, request): # get query params from get request username = request.query_params["username"] experiment = request.query_params["experiment"] If I remove the first annotator everything works fine. But when I am trying to call this function with both decorators, it does not even find the specific url path. Is it possible to use multiple decorators along with the @action decorator? -
Django unit test client login doesn't work. Why?
I've built an API using Django and Django Rest Framework. In my serializer I defined an organisation which can be posted, but needs to be stored to a different model. I defined my serializer as follows: class DeviceSerializer(serializers.HyperlinkedModelSerializer): geometrie = PointField(required=False) organisation = serializers.CharField(source='owner.organisation') owner = PersonSerializer(required=False) class Meta: model = Device fields = ( 'id', 'geometrie', 'longitude', 'latitude', 'organisation', 'owner', ) def get_longitude(self, obj): if obj.geometrie: return obj.geometrie.x def get_latitude(self, obj): if obj.geometrie: return obj.geometrie.y def create(self, validated_data): print("ORG:", validated_data.get('organisation'], "NO ORG FOUND")) # # Do some custom logic with the organisation here But when I post some json to it, which includes an organisation (I triple checked the input), it prints the line ORG: NO ORG FOUND. Why on earth doesn't it forward the organisation? -
pytest, how to keep database change between test
I'm using the following inside conftest.py @pytest.fixture(scope='session') def django_db_setup(): settings.DATABASES['default'] = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_db', 'HOST': 'localhost', } it reads data from existing DB fine. Now I want to run two tests and want the change I made in preceding tests to persist until test2 (until the whole tests in the file is finished) def test_1(): user = User.objects.get(email='a@example.com') user.username = 'hello' user.save() def test_2(): user = User.objects.get(email='a@example.com') print(user.username) # expect 'hello' but it's not there's scope `session/module' and wonder what it means, session means the whole test run? -
How to ensure uniqueness in create_or_update without db level unique constraint in Django
I am using django 1.10 with MySQL 5.7. I have a table that has a unique_together constraint on multiple columns. But few of these columns are nullable. So the DB level uniqueness is not ensured for null entries in any of these fields. I am using create_or_update method to ensure the uniqueness of rows at the application level. But in race conditions, even this does not ensure uniqueness as the system is horizontally scaled and multiple processes are concurrently trying to call the create_or_update function. I think that this should be very a normal use-case for most of the high-scale services. How do we take care of this problem? From what I think, My options can be: save a string instead of keeping the entries nullable. (but it is a foreign-key field). save a formatted string based on fields of unique together column and check uniqueness on that. I feel that both these options would be unintuitive. What's be the commonly followed best practice here? -
Is there a way I can track only the first change to a field in django models?
I have a django model Posts class Post(models.Model, ModelMeta): ... publish = models.BooleanField(default=False) date_published = models.DateTimeField(default=timezone.now) ... I want to update the date_published field only once, for the first time when publish is set to True. I have gone through Field Tracker and pre_save but both of them update on every change. I probably need to use some sort of flag that is set when publish is set to True(for the first time). Since objects can be updated and queued again, publish is again set to False before approved by an admin. I may probably add flag to the model but I think there probably should be a better way to do this? -
Set the user's profile on creation
I have a user profile model (one to one with User) that looks like this: class Profile(models.Model): user = OneToOneField(User, on_delete=models.CASCADE) facebook_id = CharField(max_length=20, blank=True) google_id = CharField(max_length=20, blank=True) def __str__(self): return self.user.email # creates a corresponding profile for the newly created user @receiver(post_save, sender=User) def user_save(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) and I would like to set the user's profile when I create a new user, so something like this: user = User( first_name=validated_data['first_name'], last_name=validated_data['last_name'], username=validated_data['username']) user.profile['facebook_id'] = social_id But this doesn't seem to work. What is the right way to do this? -
on making asynchronous django chat server i got error on running server
Unhandled exception in thread started by .wrapper at 0x000001B5D1AF5A60> Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\management\commands\runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\management__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\channels\apps.py", line 20, in ready monkeypatch_django() File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\channels\hacks.py", line 10, in monkeypatch_django from .management.commands.runserver import Command as RunserverCommand File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\channels\management\commands\runserver.py", line 11, in from channels.routing import get_default_application File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\channels\routing.py", line 9, in from channels.http import AsgiHandler File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\channels\http.py", line 152, in class AsgiHandler(base.BaseHandler): File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\channels\http.py", line 214, in AsgiHandler @sync_to_async File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\asgiref\sync.py", line 202, in init self._is_coroutine = asyncio.coroutines._is_coroutine AttributeError: module 'asyncio.coroutines' has no attribute '_is_coroutine' -
Text choices attribute not recognised
I'm trying to create a model with django-multiselectfield, but when I run python manage.py runserver I get an error saying : AttributeError: module 'django.db.models' has no attribute 'TextChoices'. I successfully installed django-multiselectfield-0.1.10 and I can't figure out why I get this error. Thanks for any help! from django.db import models from multiselectfield import MultiSelectField class MovieGenre(models.TextChoices): Action = 'Action' Horror = 'Horror' Comedy = 'Comedy' genre = MultiSelectField( choices=MovieGenre.choices, max_choices=3, min_choices=1 ) def __str__(self): return self.question_text -
Running 2 service on 2 terminal using docker-compose
I am using window 10 with docker for desktop linux container. docker-compose.yml version: '2.1' networks: my: {} services: web: build: context: . container_name: myweb command: run python manage.py runserver_plus 0.0.0.0:8000 hostname: myweb depends_on: - service networks: my: aliases: - myweb service: build: context: . container_name: myservices command: run python manage.py runserver_plus 0.0.0.0:6001 hostname: myservice networks: my: aliases: - myservice Terminal 1 docker-compose run --service-ports web Terminal 2 docker-compose run --service-ports service Service getting timeout from web. but when I run just below common docker-compose run --service-port web Then working fine. But I need to put debugger(ipdb) in both services(web/service). Can Someone please hlep me out. -
Django pass extra data to ModelSerializer create from a ModelViewSet serializer.save()
I have this ModelViewSet def create(self, request, *args, **kwargs): data_to_save = request.data pharmacy = Pharmacy.objects.get(pk=request.data['pharmacy']) serializer = self.get_serializer(data=data_to_save) serializer.is_valid(raise_exception=True) serializer.save(myArg=pharmacy) headers = self.get_success_headers(serializer.data) return Response({'results': serializer.data}, status=status.HTTP_201_CREATED, headers=headers) The self.get_serializer(...) points to a class PharmacyUserSerializer(serializers.ModelSerializer): ... The PharmacyUserSerializer(...), I'm overriding the create(...) function like so def create(self, validated_data): request = self.context['request'] myArg = self.context['myArg'] pharmacy = request.user.pharmacy user = User.objects.create_user( **validated_data, user_type=c.PHARMACY, pharmacy=pharmacy ) return user ACcording to the DRF docs, this line looks right (passing arguments to the save method) serializer.save(myArg=pharmacy) Doing the above gives the error, TypeError: 'myArg' is an invalid keyword argument for this function So what's going on? What's the right way to pass data (i guess I'm missing something in the docs). And how do I intercept this extra data in the PharmacyUserSerializer -
AttributeError: 'XXXXX' object has no attribute 'request'
I have modified_by in my model. I want someone update that it takes his user instance .I have written in model def save(self,*args,*kwargs): self.modified_by=self.request.user it gives me error above but i have written same in delete method it works.Any suggestion? -
Different language settings for website and API
I have an application with two languages, Farsi and English. This application provides a website which uses Django templates and a simple API with two endpoints using pure Django. Now I'm facing an issue I can't solve: I want the website to load in Farsi by default and the API to load in English. I have set the LANGUAGE_CODE to 'en' so everything loads in English by default. I'm not using session or cookies. Is there anyway I can tell the website to change the language to Farsi while keeping the API in English? Will I have to use cookies for this (I can't go about implementing sessions)? If so will it also affect the API? I have read the Django docs multiple times and still can't figure out the right way to go about this. Any help would be much appreciated. -
DATA_UPLOAD_MAX_MEMORY_SIZE is overriden with django 2.2.6
I was using django 1.11.23 until last month and there was no DATA_UPLOAD_MAX_MEMORY_SIZE mentioned in my settings.py. It used to allow payloads of sizes far greater than the default value of 2.5MB. However, on switching to Django 2.2.6 and (djangorestframework upgraded from 3.9.1 to 3.10.3) it has suddenly started raising the "RequestDataTooBig" Exception. Now to run the same payloads, I am forced to add DATA_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024 *100 (after seeing multiple answers here). I also switched from python 2.7 to python 3.6.8 but that ideally should not be causing any issue. -
Id field set to auth value in Django
I have a custom id field in my model that looks like this: id = models.CharField(primary_key=True, max_length=400) In my view, I render the form with the auth_id that the user signs in with in the context and then set the value of the id field in the html. See below. in my view: if request.method == 'POST': form = PersonalDetailsModelForm(request.POST) if form.is_valid(): form.save() inject(form, userdata, Section.personalDetails) return HttpResponseRedirect('/IntakeForm/2' + '?instance=' + str(form.instance.id)) else: return HttpResponse(form.errors) # else: # return render(request, 'LSPIntake/personal_details_section.html', {'soldier': form, 'auth_id':userdata['user_id']}, # {'auth0User': auth0user, 'userdata': json.dumps(userdata, indent=4)}) else: form = PersonalDetailsModelForm(label_suffix="") # get rid of default colon after labels context = {'soldier': form, 'auth_id':userdata['user_id']} # try: return render(request, 'LSPIntake/personal_details_section.html', context, { 'auth0User': auth0user, 'userdata': json.dumps(userdata, indent=4)}) in the html file: <input type="hidden" name="id" id="id_id" value={{auth_id}}> Now, whenever I sign in again to the same user, django says that the form is not valid. I think it's because it won't allow the same value to be entered into "id" twice since it is a primary_key. I want that to happen, however because if the same user signs in to their account, I don't want there to be multiple records - I want it to update an existing record. … -
BeautifulSoup won't replace string
Function doesn't throw any error but strings stay the same after execute. It look like replace_with is doing nothing. So I checked types of var's and I thing this is the problem: <class 'str'> <class 'bs4.element.Tag'> fixed_text is str and blog_text is tag type. I don't know how to resolve this problem. def replace_urls(self): find_string_1 = '/blog/' find_string_2 = '/contakt/' replace_string_1 = 'blog.html' replace_string_2 = 'contact.html' exclude_dirs = ['media', 'static'] for (root_path, dirs, files) in os.walk(f'{settings.BASE_DIR}/static/'): dirs[:] = [d for d in dirs if d not in exclude_dirs] for file in files: get_file = os.path.join(root_path, file) f = open(get_file, mode='r', encoding='utf-8') soup = BeautifulSoup(f, "lxml", from_encoding="utf-8") blog_text = soup.find('a', attrs={'href':find_string_1}) contact_text = soup.find('a', attrs={'href':find_string_2}) fixed_text = str(blog_text).replace(find_string_1, replace_string_1) fixed_text_2 = str(contact_text).replace(find_string_2, replace_string_2) blog_text.replace_with(fixed_text) contact_text.replace_with(fixed_text_2) -
Django and AJAX: Is it possible, or good practice, to submit a single form from a formset using AJAX?
My django application displays forms in formsets which are filled in by the user. These can be up to 10 forms. I have tried to work out a way to 'save' the data from a single form in this formset as this can take a long time, and users may be interrupted and not submit the entire formset, losing their work. Is this possible (or is it very bad practice?) I am thinking something along the lines of: forms.py: class ResultsForm(forms.ModelForm): result = forms.CharField( widget=forms.Textarea(attrs={'rows': 4}), required=False, label='Result') class Meta: model = Result fields = ( 'id', 'result', ) views: def save_result(request): if request.method == 'POST' and request.is_ajax(): form = ResultsForm(request.POST) if form.is_valid(): form.save() templates: {% for form in formset %} <tr> {{form.id}} <td>{{form.evidence}}</td> <td> <button id='{{ form.prefix }}-save-button' action="{% url 'results:save_result' %}" type='button' class="btn btn-info btn-sm save-result">Save</button> </td> </tr> {% endfor %} Will this work without the correct formset management? Can i isolate a form and validate it/save it using the proper django validation method? -
Heruko Time OUT
I created a django app which works perfectly fine in localhost. The SQL server is in GoogleCloud SQL. There is a simple student form registration, for which I create a form using forms.ModelForm. I use logger to find if it passed/failed the is_valid() constraint. Something like, if form.is_valid(): logging.info("passed") student = form.save() logging.info("Saved) else: logging.error("Failed") When I try with local host, it works fine in getting the POST data and creating objects in the Cloud server, but using heruko, it gets timed out. It does retrieve the POST data but times out even during checking the form, and not even print the log line of passed, giving out a timeout, but it shouldn't be a trouble regarding the SQL server because it didn't log the line in the first place to move to next step, and SQL connectivity works fine in localhost too in creating objects and posting. It throws 503 in at=error code=H12 desc="Request timeout" method=POST path="/student/register/" host=x-y.herokuapp.com request_id=----f43d65a33f03 fwd="98.210.122.173" dyno=web.1 connect=0ms service=30001ms status=503 bytes=0 protocol=https -
How to create a unique id for an entire django formset?
I have created a formset to submit project costs and i want each submission to have a unique id. I want to use the submission id in a url later on(ie "projects/1/cost-submission-edit/3"). 1 is the project's id and 3 should be the cost submission id. The formset is defined as: models.py class ProjectData(models.Model): project_name = models.CharField(max_digits = 20) client = models.CharField(max_digits= 15) class ProjectCostSubmission(models.Model): project_name = models.ForeignKey(ProjectData, max_digits = 20) cost_name = models.CharField(max_digits= 15) amount = models.DecimalField(max_digits=9) submission_date = models.DateField(auto_now_add=True) payment_approval_date = models.DateField(auto_add_now=True) forms.py class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.label_suffix = "" class Meta: model = ProjectData fields = "__all__" MyFormSet = inlineformset_factory(ProjectData,ProjectCostSubmission, form=MyForm,extra=2) views.py class ProjectCostView(CreateView): template_name = "/project_cost.html" model = ProjectCostSubmission fields = '__all__' form_class = MyForm urls.py path("/projects/<int:project_id>/cost-submission-edit/",ProjectCostView.as_view(),name="costView") After 3 submissions,the edit page renders the formset like this: Project Name Client Cost Name Amount Submission Date Approval Date ------------ ------ -------- ------ --------------- ------------- Project1 Client1 Cost A 1000.00 12/02/2019 12/03/2019 Project1 Client1 Cost B 1000.00 12/02/2019 12/03/2019 Project1 Client1 Cost C 1000.00 12/03/2019 12/03/2019 Project1 Client1 Cost A 1000.00 12/03/2019 12/03/2019 Project1 Client1 Cost F 1000.00 12/04/2019 12/04/2019 Project1 Client1 Cost G 1000.00 12/04/2019 12/04/2019 ------------------------------------------------------------------------- Total: $6000.00 ------------------------------------------------------------------------- with the url "/projects/1/cost-submission-edit/".'/1/' … -
Redis php session handling and fetching saved session on Django
I have saved php session in redis using php session handler and i want to read that session value in Django. The issue is I am getting a byte sting on Django side which seems to be incorrect format for me as I want the value direct by just passing the key to redis server. I want "This is shahiq" only as a result ? -
Is there a way to avoid Gatsby from breaking when a GraphQL node is empty from a Django Rest Framework source?
I am trying to make a simple blog using Gatsby and Django REST Framework for my endpoints. Along with returning the title and content, I am also returning a tags field which could be an array of object and an empty array when the post contains no tags. The error comes up when I try querying a post with no tags (i.e having an empty array). Gatsby breaks since GraphQL cant go forward into querying the children nodes. This is my GraphQL query from my Gatsby page: query MyQuery { allRestApiPosts { edges { node { tags { id tag { color name } } id content title author { profile { first_name last_name profile_photo } } } } } } And the page breaks with this error: There was an error in your GraphQL query: - Unknown field 'tags' on type 'RestApiPosts!'. How can I avoid this error when there are no tags attached to a post? -
Django: inner function with request as parameter
In my views.py, I have the following Function Based View: # Create your views here. @login_required def initial_load(request): # only superusers can upload documents if request.user.is_superuser: if request.method == 'POST': # get the excel sheet excel_file = request.FILES["ExcelFile"] # perform validations validate_uploaded_excel(request, excel_file) # upload file to Document print("still executing") form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('pages:home') return redirect('pages:home') form = DocumentForm() return render(request, 'excel/initial_load.html', {'form': form}) else: messages.warning(request, "You are not a superuser") return redirect("pages:home") as you can observe, I have the function validate_uploaded_excel which has the following code: def validate_uploaded_excel(request, excel_file): message_list = [] # retrieve the sheet names allowed _list = settings.EXCEL_ALLOWED_SHEET_LIST_INDICATORS # check if the sheets names is the one expected (validated, message_sheets) = excel_utils\ .validate_excel_sheet_names(excel_file, _list) message_list.append(message_sheets) # If no errors detected if validated: messages.success(request, "File format is correct") return redirect('pages:home') else: for mess in message_list: # When there was no error, message was set to none if mess is not None: messages.warning(request, mess) return redirect('excel:initial_load') I though that the redirect from validate_uploaded_excel would just redirect to the page, but it seems that Django uploads the file no matter the output of validate_uploaded_excel. How is this possible? How can I avoid such behavior? -
Django Rest Framework - how to save data based on foreign key
I'm working on an app where a user uploads a file. The user chooses a "Project" to assign the file to. Each project is assigned a "user" and an "editor". When the file is uploaded, I'm trying to set the owner of the file based on the "user" from the "project". Project Model: class Project(models.Model): projectCode = models.CharField(max_length=10) projectName = models.CharField(max_length=100) user = models.ForeignKey( User, related_name="projects", on_delete=models.CASCADE, null=True) editor = models.ForeignKey( User, on_delete=models.CASCADE, null=True) creationDate = models.DateTimeField(auto_now_add=True) completedDate = models.DateTimeField(null=True, blank=True) dueDate = models.DateTimeField(null=True, blank=True) def __str__(self): return f"{self.projectName}" Model for the file being uploaded: class Completed(models.Model): completed = models.BooleanField(default=False) url = models.CharField(max_length=100) handle = models.CharField(max_length=30) filename = models.CharField(max_length=100) size = models.IntegerField() source = models.CharField(max_length=50) uploadId = models.CharField(max_length=50) originalPath = models.CharField(max_length=50) owner = models.ForeignKey( User, related_name="completed", on_delete=models.CASCADE, null=True) project = models.ForeignKey( Project, related_name="projectId", on_delete=models.SET_DEFAULT, default=1) uploadDate = models.DateTimeField(auto_now_add=True) editor = models.ForeignKey( User, related_name="editor", on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.filename}" Project Serializer: class ProjectSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Project fields = '__all__' Serializer for file uploaded: class CompletedSerializer(serializers.ModelSerializer): project = ProjectSerializer(read_only=True) owner = UserSerializer(read_only=True) editor = UserSerializer(read_only=True) class Meta: model = Completed fields = '__all__' And finally, the viewset for the uploaded file: class CompletedViewSet(viewsets.ModelViewSet): permission_classes = [ … -
How can I extract cookies of browser(or a particular site) using python or django?I am trying with the following code
import browser_cookie3 import requests import re cj=browser_cookie3.chrome() r=requests.get('https://www.youtube.com/', cookies=cj) get_title = lambda html: re.findall(('(.*?)'), html, flags=re.DOTALL)[0].strip() get_title(r.content) And i am getting the following error- TypeError: cannot use a string pattern on a bytes-like object (It get in line 6.) -
How to edit django DRF API code that queries DB and returns data, to read in a file and upload data
I know there are a lot of questions like this out there, I'm just really confused about my specific case. I have a employee_models.py file with three classes; one with employee names and one with dept details, and then one that combines these two and some other info: from django.db import models class employee_name(models.Model): id=models.AutoField(primary_key=True) first_name = models.CharField(max_length=100, blank=True, null=True) surname = models.CharField(max_length=100, blank=True, null=True) middle_initial = models.CharField(max_length=100, blank=True, null=True) class employee_dept(models.Model): id = models.AutoField(primary_key=True) employee = models.ForeignKey('employee_name',blank=True, null=True) dept_name = models.CharField(max_length=100, blank=True, null=True) time_in_dept = models.CharField(max_length=100, blank=True, null=True) due_review = models.CharField(max_length=100, blank=True, null=True) class full_employee_record(models.Model): id = models.AutoField(primary_key=True) name = models.ForeignKey('employee_name',blank=True, null=True) dept = models.ForeignKey('employee_dept',blank=True, null=True) address = models.CharField(max_length=100, blank=True, null=True) benefits = models.CharField(max_length=100, blank=True, null=True) I have a serializers.py file: from rest_framework import serializers from employee_models import employee_name,employee_dept class EmployeeNameSerializer(serializers.ModelSerializer): class Meta: model = employee_name fields = "__all__" class EmployeeDeptSerializer(serializers.ModelSerializer): class Meta: model = employee_dept fields = "__all__" class FullEmployeeRecordSerializer(serializers.ModelSerializer): class Meta: model = full_employee_record fields = "__all__" and a Views.py file: class EmployeeNameViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list` and `detail` actions. """ queryset = employee_name.objects.all() serializer_class = EmployeeNameSerializer permission_classes = (permissions.IsAuthenticated, CuratedDataPermission) pagination_class = LongPagination class EmployeeDeptViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list` and `detail` actions. … -
How should I write my Models in django(This case is a little specific)?
I am in a bit of a weird situation right now and hence this question. Say I have a game and I have a website that shows stats for all its players. Now my problem is that I have a bunch of levels and I want to show stats like personal best(least no of moves or time) and stuff for each level to each player on my website. Now if I have to store all this data for each player, how would I do so? Originally I thought why not a table each for a player which has columns of level no, personal best and so on. But, then I would have a 100 tables (or models in this case of django) if I had 100 players and querying for a leaderboard and stuff becomes a problem. So my next best solution I thought was maybe have a table (model) with player names and have as many columns as there are levels and values for each entry would be their personal bests. But, then if I added more levels, scalability becomes an issue and it isn't an elegant solution either. So this is my problem, it isn't very technically to …