Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Multiple Nested Writable Serializers
I am trying to implement multiple nested writable serializers using django rest framework. I have read the docs available http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations I have been able to do this for one level nests but have a problem when there are multiple nests. For example, I have these 3 serializers: class FarmerSerializer(serializers.ModelSerializer): dob = serializers.DateField(write_only=True) gender = serializers.CharField(write_only=True) farms = FarmSerializer(required=False, many=True) class Meta: ... def create(self, validated_data): # check if nested objects were provided, in particular farms farms = validated_data.pop('farms', None) farmer = Farmer(**validated_data) farmer.added_by_id = validated_data.get('added_by_id') farmer.save() if farms is not None: for farm in farms: new_farm = Farm.objects.create(farmer=farmer, added_by=farmer.added_by, **farm) # check for blocks -- fails blocks = farm.pop('farm_blocks', None) if blocks is not None: for block in blocks: FarmBlock.objects.create(farm=new_farm, added_by=farmer.added_by, **block) return farmer class FarmSerializer(serializers.ModelSerializer): county = CountySerializer(read_only=True) county_id = serializers.UUIDField(write_only=True) farm_blocks = FarmBlockSerializer(required=False, many=True) class FarmBlockSerializer(serializers.ModelSerializer): ... I'd like to be able to post JSON that is nested and save all 3 levels i.e farmer, farms and farm blocks. It currently works when I'm saving the first 2 levels i.e Farmer and associated farms. If it helps, here is the JSON structure I'm attempting to save: [ { "name": "Ashley King", "phone_number": "0765124764", "gender": "F", "dob": "1980-11-26", "national_id": … -
Django_tables2 - part of css not working
This is my first time working with the django_tables2 plugin - so naturally, I followed the installation and quick start guide in their docs. I have pip-installed django-tables2, added 'django_tables2' to my installed apps, and made sure that 'django.template.context_processors.request' was in the template options. However, I've come across a weird anomaly. I'm pasting my code below, for reference - Views - from django.shortcuts import render from .models import VM def people(request): return render(request, 'home.html', {'vms': VM.objects.all()}) home.html - {% load render_table from django_tables2 %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="{% static 'css/bs.css' %}" /> <link rel="stylesheet" href="{% static 'django_tables2/themes/paleblue/css/screen.css' %}" /> <link rel="stylesheet" href="{% static 'css/style.css' %}" type="text/css" /> </head> <body> <div class="col-sm-offset-2 col-sm-10 text-center"> <h2 id="Text">VM List</h2> {% render_table vms %} </div> </body> </html> As you can see, this is exactly what's given in the docs. However, while my table is somewhat formatted, it isn't completely the same as what I originally expected. This is what I get - And this is something I should be getting, according to the docs. - Note that the django_tables2 css is in fact fetched. I kept an eye on the source files, and the … -
Django: ImportError: No module named 'scipy.sparse.base'
For my project I am using Scipy, but as it seems, my project has trouble in importing stuff from it. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f2f4244f400> Traceback (most recent call last): File "/home/betaros/.local/lib/python3.5/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/betaros/.local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/home/betaros/.local/lib/python3.5/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/betaros/.local/lib/python3.5/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/betaros/.local/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/betaros/.local/lib/python3.5/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/betaros/.local/lib/python3.5/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/home/betaros/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/home/betaros/.local/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/betaros/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/betaros/.local/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/betaros/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 673, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/betaros/PycharmProjects/nsg-lfp/webFrontEnd/webFrontEnd/urls.py", line 20, in <module> url(r'^pass_list/', … -
Django deploying website
I have made the tool(website) in the django.I want to deploy this application in the production. Now I am confused about several things.At the time of the development I can run my application using the command: python manage.py runserver IP_OF_SERVER:PORT. Now by this approach I can do all the things.My tool(website) will be only used locally. Is it fine that I deploy my Tool(site) with this command only?Is is necessary to do the django production processes and if it is necessary how to do that?I am new to django. Please help me to understand. -
How to redirect to a different domain's url with post data
I have a single page application, which will post JSON data to the URL on Django backend server. When this view is called from its URL, I need it to redirect to a different URL (different domain). def Buy(request): key = 'some_key' txnid = 'some_id' amount = 10.00 firstname = 'TestF' surl = 'http://site.in/buy/success' furl = 'http://site.in/buy/fail' hash = '' salt = 'some_salt' hash_list = [key, txnid, str(amount), firstname, salt] hash_seq = "|".join(hash_list) hashed = hashlib.sha512(hash_seq) hashed_hexdigest_lower = hashed.hexdigest().lower() data = { "key": key, "txnid": txnid, "amount": amount, "firstname": firstname, "surl": surl, "furl": furl, "HASH": hashed_hexdigest_lower } url = "https://test.site.in/payment" return redirect(url, kwargs=data) Basically, when the redirect happens, I want to post the above data to that URL like a form submission. How can I do this in Django? -
Unable to implement django-rules authorization
I'm a new django user looking for some help with django-rules. I'm trying to set up an authorization system that is OR based. I have a 'Bill' model. I would like only the creator to be able to delete it, but a specific set of users to edit it. I've been able to followed their tutorial and implementation throughout; it works in the shell but not on my site. At the moment any user can delete anything. My view currently looks like: class BillDeleteView(generics.RetrieveDestroyAPIView, PermissionRequiredMixin): """ View for deleting a bill """ queryset = Bill.objects.all() serializer_class = BillSerializer permission_required = 'bills.delete_bill' And in my admin I created the permissions like so: class FileAdmin(ObjectPermissionsModelAdmin): list_display = ('owner', 'name', 'file', 'source', 'date') rules.add_perm('fileupload.change_file', my_rules.is_creator | my_rules.is_editor) rules.add_perm('fileupload.delete_file', my_rules.is_creator) admin.site.register(File, FileAdmin) The rules have been created in my rules.py file and work. I know I'm close I feel like I'm just missing one step. Thanks in advance! -
what is defference between django rest framwork's 'serializer' and 'serializer fields'
The serializer of django rest framework converts the model data to JSON format and validates incoming data Check function. The functions of the serializer fields are to convert values and data types and to validate input values. I think it looks the same, but I wonder what the difference is. -
How to remove some warning messages using Django and Python
I need some help. I am getting some warning messages while formatting my code using pylint. I am explaining those warning messages below. C: 77, 0: Line too long (82/80) (line-too-long) C:125, 0: Line too long (83/80) (line-too-long) E: 76,13: Class 'Service' has no 'objects' member (no-member) E:106,19: Class 'Personal' has no 'objects' member (no-member) I am explaining my code below. def view_service(request): """ This function helps to display the past booking items""" people = Service.objects.all() return render(request, 'bookingservice/view_service.html', {'people': people}) models.py: class Service(models.Model): """In this class the columns for service table has declared""" cname = models.CharField(max_length=200) date_of_service = models.DateTimeField(default=datetime.now, blank=True) vechile_no = models.CharField(max_length=200) service_type = models.CharField(max_length=200) class Personal(models.Model): """In this class the columns for Person table has declared""" name = models.CharField(max_length=200) address = models.CharField(max_length=200) phone = models.CharField(max_length=15) driving_license = models.CharField(max_length=200) email = models.CharField(max_length=200) date = models.DateTimeField(default=datetime.now, blank=True) In the above function last line is showing too long and another warning related to Service class is also there. Here I need to remove both of the warning messages. Please help. -
Running Django function every n insert to a specific model
Is there a way to run a piece of code in Django when say 128 new entries are made to a specific model? -
how to use lampp server for django?
i want to use lampp localhost for hosting my django mywebsite. and to create database for website in lampp in django DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #'NAME': os.path.join(BASE_DIR, ''), 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASSWORD', 'HOST': '127.0.0.1', 'PORT': '3306', } -
Django Rest - Cant serialize items
I'm trying to serialize nested relations, but got an error during create model from request: 'MeasureUnit' object has no attribute 'unit' What am I doing wrong? I'm just trying to create model MeasureItem, but got error in MeasureUnit somehow. My models: from django.db import models from measure_unit.models import MeasureUnit from main_user.models import MainUser class Item(models.Model): code = models.CharField(unique=True, max_length=15) current_code = models.CharField(blank=True, null=True, max_length=15) title = models.CharField(default='', max_length=100) description = models.TextField(blank=True, null=True) measure_units = models.ManyToManyField(MeasureUnit, through='MeasureItem', through_fields=('item', 'unit'), blank=True) class Meta: ordering = ('created_at',) class MeasureItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, blank=True, null=True) unit = models.ForeignKey(MeasureUnit, on_delete=models.CASCADE, blank=True, null=True) quantity = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('created_at',) My serializer: from rest_framework import serializers from .models import Item, MeasureItem class MeasureUnitSerializer(serializers.ModelSerializer): class Meta: model = MeasureItem fields = ('id', 'unit') class ItemAdminSerializer(serializers.ModelSerializer): measure_units = MeasureUnitSerializer(many=True) class Meta: model = Item fields = ('id', 'code', 'current_code', 'title', 'description', 'measure_units') def create(self, validated_data): units_data = validated_data.pop('measure_units') item = Item.objects.create(**validated_data) for unit_data in units_data: try: measure_unit = unit_data['unit'] MeasureItem.objects.create(unit=measure_unit, item=item) except Exception as e: print(str(e)) return item return item -
clear input filed when clear button is pressed in Django
i have an input field in django html file and a clear button and i want to clear the input filed when the clear button is pressed. how can it be done? do i need to know javascript for that or it can be done otherway? <form> <input type="text" id="textfield1" size="5"> <input type="text" id="textfield2" size="5"> <input type="reset" value="Reset"> </form> i want to clear only one field not both -
Creating Inline formsets with many to many relationships
I have been learning django for a few weeks, Now I am trying to use inlineformset_factory to create related objects via foreign key, but I am having an error when creating the formset. These are my models: class Question(models.Model): content = models.TextField(max_length=1000,blank=False,verbose_name='Question') created_by = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Author") created_date = models.DateTimeField(default=timezone.now) class Anwsers(models.Model): content = models.TextField(max_length=1000,blank=False,verbose_name='Answer') options = models.ManyToManyField(Anwsers,through='QuestionAnswers') class QuestionAnswers(models.Model): question = models.ForeignKey(Question) anwsers = models.ForeignKey(Anwsers) correct = models.BooleanField(blank=False,verbose_name="Correct") I tried to create the formset like this: AnwsersInlineFormSet = inlineformset_factory(QuestionAnswers,Anwsers.options.through) and this is the error I'm getting: ValueError: 'question.QuestionAnswers' has no ForeignKey to 'question.QuestionAnswers'. -
403 error with large media files
I'm running a Django server hosted on DigitalOcean using Nginx and Gunicorn. I tried adding a 2MB picture via the admin interface when I get hit with a 403 error. Looking into error.log indicated permission was denied, as follows: 2017/06/27 01:03:29 [error] 1643#1643: *30 open() "/home/brian/nydkc11/nydkc11/nydkcd11/media/image_main/dtc1.jpg" failed (13: Permission denied), client: 108.29.217.25, server: nydkc11.org, request: "GET /media/image_main/dtc1.jpg HTTP/1.1", host: "nydkc11.org", referrer: "http://nydkc11.org/admin/blog/image/7/change/" The weirdest thing, however, is that smaller image files work just fine (around 18 kb or so). Anyone know why larger media files may be triggering the problem, and how I should fix it? I had to set client_max_body_size to 100M in my nginx.conf, if that's a useful think to know. -
get_or_create returning error that multiple value of objects exist
I am trying to use get_or_create method to see if a record exists. If the record exists do nothing otherwise create it. This model is basically used on the command that is failing class modelStudentExamsPerformed(models.Model): patient = models.ForeignKey(modelPatient) student = models.ForeignKey(modelStudent,on_delete=models.CASCADE) normalBodyPart = models.ForeignKey(modelNormalBodyPartResult,default=None,blank=True,null=True) abnormalBodyPart = models.ForeignKey(modelAbnormalBodyPartResult,default=None,blank=True,null=True) tool = models.CharField(max_length=128, default="") Now this is the command that is using the above model and failing exams.modelStudentExamsPerformed.objects.get_or_create()(patient=patient_qset, student=stud_qset,abnormalBodyPart=qset[0],normalBodyPart=None,date=None) The above statement gives me the error : get() returned more than one modelStudentExamsPerformed -- it returned 2! Now this is where I am having trouble. When I look into the database through my admin I do notice two objects but those objects both have a value associated with normalBodyPart and their abnormalBodyPart is empty.Since I explicitly specified and assigned a value to abnormalBodyPart why does django say that two items already exist ? I hope this makes sense . Let e explain this another way as well suppose there are two statements 1 and 2. Statement 1 gets or creates a record based on a specified parameter . This get or create fails as django thinks there are already two records. However statement 2 uses the same exact parameters and returns 0 records. … -
How to transform this rules into code in python?
I would like some HELP!! I want to make a simple noob function before put into my django project. I want a function that provides the lamp power of a room. Input: The room's area (m²) Output: The lamp power (W). The rules of this math is: If the entry area is <= 6m² then the power will be 100W (easy). If the area is > 6m² then for the first 6m² the power is 100W, BUT for the next 4m² is added 60W to the lamp power. Ex: Area = 20m² 6m² + 4m² + 4m² + 4m² + 2m² = 20 m² 100 + 60 + 60 + 60 + 0** = 280 W **(less than exact 4m² doesn't count) def light(area): power = 0 if area < 6: power = 100 else: ........ return power print(light(20)) Any help to make this simple code would be AWESOME! -
Performance issues with weave networking on Kubernetes cluster
I create a Kubernetes (v1.6.1) cluster on AWS with one master and two slave nodes, then I spin up mysql instance using helm and deploy a simple Django web-app that queries latest five rows from the database and displays it. For my web service I specify 'type: LoadBalancer' which creates an ELB on AWS. If I use 'weave' networking and scale my web-app to at least two replicas, then I begin experiencing inconsistent response time - most of the time it is reasonable (like 0.1-0.2 s), but 20-40% requests take significantly longer (3-5 s, sometimes even more than 15 s). However, if I switch to 'flannel' networking, everything works fast, even with 20-30 replicas of the web-app. All machines have enough resources, so that's not the problem. I tried debugging to find out what's causing the delay, and the best explanation I have is that AWS ELB doesn't work well with 'weave'. Has anyone experienced similar issues? What could be the problem? Please let me know if I should provide some relevant information. P.S. I'm new to using Kubernetes. -
django - Filter items list
I have a web page made with Django thats show albums of music. I want to add filters in order to show albums that have special singer for example and add a boutton to sort by name. -
Django 1.6, all() throws error: Cannot set values on a ManyToManyField which specifies an intermediary model
I am having an exception in Django 1.6 with Python 2.7.13 (x86), and I don't know to to fix this. I already searched other posts for the answer, but to no avail. I am stuck on this, and have been spinning my wheels for a while. This is the line of code that throws the exception: myNewClass.class_students = selectedClass.class_students.all() Please see the complete code example below... This is the error message that I am getting: Cannot set values on a ManyToManyField which specifies an intermediary model. Use MyApp.ClassStudents's Manager instead. (For the above error message, my app is called 'MyApp'...) It seems like all() does not work, is there anyway to fix this? Can you guys please help me fix this or at least point me in the right direction... Thanks. Here is my code: class Class(models.Model): courseNumber = models.IntegerField() courseName = models.CharField(max_length = 32) class_students = models.ManyToManyField(Student, blank = True, through = 'ClassStudent') class Student(models.Model): studentName = models.CharField(max_length = 32) overallStudentGPA = models.IntegerField() class ClassStudent(models.Model): myClass = models.ForeignKey(Class, on_delete = models.CASCADE) myStudent = models.ForeignKey(Student, on_delete = models.CASCADE) studentClassGrade = models.IntegerField() def copy_class(modeladmin, request, queryset): for selectedClass in queryset: myNewClass = Class(courseNumber = selectedClass.courseNumber, courseName = selectedClass.courseName) myNewClass.courseNumber = selectedClass.courseNumber … -
How to get the values of a request in Python?
I get this result when I print the request, which arrived at a POST. <QueryDict: {u'form_values': [u'nombre=Juan&apellidos=Perez&correo=juan@email.com&confiCorreo=juan@email.com&telefono=5598764&celular=8971265256&calle_numero=Calle+#10&colonia=San+Pablo&municipio=&estado=&pais=&cPostal=&razonS=&rfc=&callenumero=&colonia=&municipio=&estado=&codPos='], u'pass': [u'k7iwriilqm66mtnu2m1x'], u'csrfmiddlewaretoken': [u'kkxdVbDzPXhfDazzSVvIvAYizExoRSFR'], u'clabe': [u'8jO9ChGsKXJfrBtb4vBMsxQKdA8L7Y0h']}> How can I get the values that come from form_values individually (nombre, apellidos)? -
Declaring a Django signal inside a method
I'm trying to remove a file that I've created after it's been sent to the user: def download_file(request, contents): f = NamedTemporaryFile(delete=False) def test_signal(sender, **kwargs): print 'finished' os.remove(f.name) request_finished.connect(test_signal) f.write(contents) f.close() response = HttpResponse(FileWrapper(open(f.name)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename=%s' % smart_str('file.txt') return response Downloading the file works fine, but the signal won't get triggered. What puzzles me is that it does work when I put test_signal() outside of the download_file(), i.e. declaring it above at the same level, but if I do that I can't access the name of the file to remove. Why can't I use test_signal() when it's declared inside this method? -
Django: TypeError: context must be a dict rather than str
I wanto to redirect to an url if the object of GroupMember doesn't exist but shows this error: TypeError: context must be a dict rather than str. Here is my view: class GroupDetail(DetailView): template_name = "group_detail.html" model = Group def get_context_data(self, **kwargs): context = super(GroupDetail, self).get_context_data(**kwargs) # Code try: group_member = GroupMember.objects.get(member=volunteer, group=group) context['group_member'] = group_member # Code return context except: return reverse('users:home') I try with redirect and reverse_lazy but shows the same error an try with reverse('users:home', {}), reverse('users:home', kwargs={}) and reverse('users:home', kwargs=None) -
Firebase message not received by browser
I have a Django project in which I use Firebase cloud messaging to power up push notifications. Here is my code: index.html <script> var config = { // ... }; firebase.initializeApp(config); const messaging = firebase.messaging(); navigator.serviceWorker.register('/static/firebase-messaging-sw.js').then((registration) => { messaging.useServiceWorker(registration); messaging.requestPermission().then(function() { console.log('Notification permission granted.'); return messaging.getToken(); }).then(function(token){ $.post('/a_send_fcm_token/', {'fcm_token_web': token}); }).catch(function(err){ console.log('Error ocurred'); }); }); messaging.onMessage(function(payload) { console.log('Hoorah'); // does not work :( }); </script> Because Django project layout has certain peculiarities, I use navigator.serviceWorker.register() function in the above code to change the default location of firebase-messaging-sw.js file which would otherwise be in the root directory of the project. My firebase-messaging-sw.js looks like this: importScripts('https://www.gstatic.com/firebasejs/4.1.2/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/4.1.2/firebase-messaging.js'); var config = { apiKey: "AIzaSyCvt-sddXFg7Kjrttu42O6nagQIbo58bbY", authDomain: "android-blend-4b456.firebaseapp.com", databaseURL: "https://android-blend-4b456.firebaseio.com", projectId: "android-blend-4b456", storageBucket: "android-blend-4b456.appspot.com", messagingSenderId: "1024370094646" }; firebase.initializeApp(config); const messaging = firebase.messaging(); And finally, my Django view which posts message to FCM: headers = {'Authorization': "key=AAAA7oE3MjY:APA91bE_M-BtgujBl2p5s2NQ2WPjseWx7c6CET5s-xMcbCzxWYm7Odk-FOPN9RDVi-_3vozaSZeWUaj02vWe_3GDSWyHU8qozODhfxSohbR5hi7thBO3gjWEdnZKnABggKL8pat7IDSr"} user_web_tokens = UserWebTokens.objects.filter(user = request.user)[0].token payload = {"data": {}, "to": user_web_tokens} r = requests.post("https://fcm.googleapis.com/fcm/send", data=payload, headers=headers) return True It seems like I've implemented most of the stuff correctly because I succeed in obtaining token from FCM. But I can't make FCM to the message to me, so: The question: Why doesn't my messaging.onMessage() work ? -
Indexing and searching related objects with haystack
I'm pretty new to search implementation, bear with me while I'm learning! So my pet project is a recipe site and each recipe can have n steps. the model looks something like: class Recipe(models.Model): title = models.CharField(max_length=255) description = models.TextField() hotness = models.ForeignKey(Hotness) recipe_diet = models.ManyToManyField(DietType) ingredients = models.ManyToManyField(Ingredient, through="RecipeIngredient") class DietType(models.Model): diet_type = models.CharField(max_length=50) description = models.TextField(null=True, blank=True) class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe) ingredient = models.ForeignKey(Ingredient) quantifier = models.ForeignKey(Quantifier) quantity = models.FloatField() class RecipeSteps(models.Model): step_number = models.IntegerField() description = models.TextField() recipe = models.ForeignKey(Recipe) (shortened for brevity) I want to index all of it: Recipe, RecipeIngredient, DietType and Steps... The DietType and RecipeIngredient seem to be working fine, but the Steps are not. I assume this has to do with the usage of 'RelatedSearchQuerySet' ? Here is my search_indexes.py: from haystack import indexes from recipes.models import Recipe class RecipeIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr='title') ingredients = indexes.MultiValueField(indexed=True, stored=True) description = indexes.CharField(model_attr='description') hotness = indexes.CharField(model_attr='hotness') diet_type = indexes.MultiValueField(indexed=True, stored=True) recipesteps = indexes.MultiValueField(indexed=True, stored=True) def prepare_steps(self, object): return [step.description for step in object.recipesteps.all()] def get_model(self): return Recipe def load_all_queryset(self): # Pull all objects related to the Note in search results. return Recipe.objects.all().select_related() Here is the template recipe_text.txt: {{ object.title … -
What is the most efficient way to create models for storing tags in Django 1.9 and Postgres 9.5?
I want to make a model where I have the option of pulling a group of items and their descriptions from a postgres database based on tags. What is the most efficient way of doing this for performance using Django 1.9 and Postgres 9.5? I found multiple ways of doing this: Toxi solution Where 3 tables are made, one storing the item and descriptions, second storing the tags, and a third table associating tags with items. See here: What is the most efficient way to store tags in a database? Using Array fields Where there is one table with items, descriptions, and an array field that stores tags Using JSON fields Where there is one table with items, descriptions, and an JSON field that stores tags. The django docs mention this uses JSONB: https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/ I am guessing that using JSON fields like the following: from django.contrib.postgres.fields import JSONField from django.db import models class Item(models.Model): name = models.CharField() description = models.TextField(blank=True, null=True) tags = JSONField() is the most efficient but I am not really sure.