Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django One queryset to rule millions of them
We have a key-value datastore, defined by the following models : models.py #Table with millions of entries class Person(models.Model): name = models.CharField() group = models.ForeignKey(Group) # Table with few entries class Program(models.Model): name = models.CharField() # Table with hundreds of entries class ResultType(models.Model): name = models.CharField() type = models.CharField() # Huge table with billions of entries class Result(models.Model): person = models.ForeignKey(Person, related_name='gotten_results') program = models.ForeignKey(Program, related_name='given_results') result_type = models.ForeignKey(ResultType, related_name='type_results') value = models.CharField() So what I want to achieve is to get for a given list of 'Person', the programs that gives at least one result and count it at program level. For the moment, what I did is the following : def my_function(given_group): persons = Person.objects.filter(group=given_group) programs = Program.objects.all() given_results = {} for program in programs : given_results[program.name] = 0 for person in persons : # if the program gave at least one result to the person if ResultValue.objects.filter(program=program, person=person).exists() : given_results[program.name] += 1 else: continue return given_results That is the easiest way to do it (2sec thinking) but if my given_group contains one million of person, that is a terrible way to do it. The other solution solution that came to my mind is to use select_related/prefetch_related but … -
Rendering streamfield block a certain way if booleanBlock is True
Hello I'm currently new to django/wagtail. I'm working on an about page that shows previous and current work/positions. I've made the positions streamfield blocks since the amount of experience isn't limited. Here is the code to my models. #Create experience block class ExperienceBlockStruct(StructBlock): position_title = CharBlock(help_text="Enter a previous position title.") description = CharBlock(help_text="Job description") current_position = BooleanBlock(required=False, help_text="Check if current position") class Meta: template = 'blocks/experience_block.html' class ExperienceBlock(StreamBlock): experience = ExperienceBlockStruct(icon="form") And here is the page where I use the models class About(Page): profile_pic = "some image reduced code bc it currently works" bio = RichTextField(blank=True) resume = "some document reduced code bc it currently works" experience = StreamField(ExperienceBlock()) content_panels = Page.content_panels + [ ImageChooserPanel('profile_pic'), FieldPanel('bio'), DocumentChooserPanel('resume'), StreamFieldPanel('experience'), ] Now the issue I'm having is how to render the blocks where the current_position = True in a different area than those that are not. I've tried templates/about.html {% for block in page.experience %} {% if block.current_position %} {% include_block block %} {% endif %} {% endfor %} But that doesnt render anything. I've also tried to <div class="experience"> {% if value.current_position %} {{ value.position_title }} {% else %} {{ value.position_title }} {% endif %} </div> but that creates a new … -
DigitalOcean django upgrade to python3
i followed this tutorial deploying my django server. https://www.youtube.com/watch?v=Y-CT_l1dnVU&t=1171s&index=11&list=PLQVvvaa0QuDeA05ZouE4OzDYLHY-XH-Nd using digital ocean one-click django setup. what i want to do is upgrading my vps to use python3. that simple. anybody done this before? how? -
Django: dynamic models disappear after creation
Let's say I have 2 models. Model_A and Model_B. Whenever the admin user makes a change to an object of model_A, they click the "save" button. So, when a "save" happens, I would like to send a post_save signal that creates a model that inherits from Model_B. When I do so like the following, the models do get created but they disappear after refreshing the page, and sometimes they appear again after refreshing again. But they don't always stay on the list. (Weird, I know!) So the code for the post_save signal is like so: post_save.connect(create_new_model, sender=Model_A) My create_new_model is like so: def create_new_model(sender, instance, **kwargs): attrs = { 'field1': models.CharField(max_length=40), 'field2': models.CharField(max_length=40), '__module__': 'appname.models' } from appname.models import create_model, admin_options, modelsList mod = create_model(name=str(len(modelsList)), fields=attrs, admin_opts=admin_options ) modelsList.append(mod) And finally, the function that creates the dynamic models (create_model) is like so: def create_model(name, fields=None, admin_opts=None): from appname.models import Model_A attrs = fields model = type(name, (Model_A,), attrs) if admin_opts is not None: admin.site.register(model, admin_opts) return model Does anyone know why this sneaky thing might be happening? -
Django admin : show records for respective user only
I have a simple model, say Resources. And I have fewer than 20 users and model admin serves the purpose to record requests. Problem is that all users can see all records in model admin site. Can this behaviour be changed to only show records created by same user only ? Thank you in anticipation. -
What does related_name do?
In the Django documentation about related_name it says the following: The name to use for the relation from the related object back to this one. It’s also the default value for related_query_name (the name to use for the reverse filter name from the target model). See the related objects documentation for a full explanation and example. Note that you must set this value when defining relations on abstract models; and when you do so some special syntax is available. If you’d prefer Django not to create a backwards relation, set related_name to '+' or end it with '+'. I didn't understand it clearly. If somebody would please explain it a bit more, it would help me a lot. -
ValueError: Missing staticfiles manifest entry for 'favicon.ico'
I'm getting a ValueError when running python manage.py test. My project is named fellow_go, and I'm currently working on an App called pickup. Please note that this error is added in a relatively recent commit to Django: Fixed #24452 -- Fixed HashedFilesMixin correctness with nested paths.. ====================================================================== ERROR: test_view_url_exists_at_desired_location (pickup.tests.test_view.HomePageViewTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/sunqingyao/PycharmProjects/fellow_go/pickup/tests/test_view.py", line 10, in test_view_url_exists_at_desired_location resp = self.client.get('/', follow=True) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/test/client.py", line 536, in get **extra) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/test/client.py", line 340, in get return self.generic('GET', path, secure=secure, **r) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/test/client.py", line 416, in generic return self.request(**r) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/test/client.py", line 501, in request six.reraise(*exc_info) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/utils/six.py", line 686, in reraise raise value File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/core/handlers/base.py", line 215, in _get_response response = response.render() File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/template/response.py", line 107, in render self.content = self.rendered_content File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/template/response.py", line 84, in rendered_content content = template.render(context, self._request) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/template/backends/django.py", line 66, in render return self.template.render(context) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/template/base.py", line 207, in render return self._render(context) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/test/utils.py", line 107, in instrumented_test_render return self.nodelist.render(context) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/template/loader_tags.py", line 177, in … -
Are django custom model manager methods thread safe?
I am trying to implement custom model manager for django models. My only question is that are these methods (implemented in custom model manager) thread safe ? Note: below is an example class PollManager(models.Manager): def get_by_code(self, code): try: obj = self.model.objects.get(code=code) return obj.__dict__ except ObjectDoesNotExist as e: return None class OpinionPoll(models.Model): question = models.CharField(max_length=200) poll_date = models.DateField() code = models.CharField(max_length=200) objects = PollManager() Is "get_by_code" method in custom model manager thread safe ? I am using it like OpinionPoll.objects.get_by_code(some_code) django = 1.10.5 ,python = 2.7 -
What is the scope of Django's Middlewares?
What is the scope of Django's Middleware objects? I wish to know if the Middleware objects are initialized for every request. Relevance: While trying to use SQLAlchemy ORM along with Django, one needs to point a callable object as the scope marker to use the SQLAlchemy's scoped_session. And I'm trying to set the SQLAlchemy session in request scope. -
Need to have a Required and Optional Fields in Django Formset
I created a formset that has maximum of 5 images to be attached, but I want the Validation to run only when the user has not attached any image(ValidationError('atleast 1 image is required')), So if there is 1 image or 2, that should be allowed to save. template <form enctype="multipart/form-data" action="" method="post"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {{ form.as_p }} {{ formset.management_form }} <div class="link-formset"> {% for choice in formset %} <div> <label>{{ choice.media }}</label> <input type="radio" name="featured">{{choice.featured_image.label }} </div> {% endfor %} </div> <input type="submit" value="{{ submit_btn }}"> </form> forms.py class ProductImagesForm(forms.ModelForm): media = forms.ImageField(label='Image', required=True) featured_image = forms.BooleanField(initial=True, required=True) class Meta: model = ProductImages fields = ['media', 'featured_image'] ImagesFormset = modelformset_factory(ProductImages, fields=('media', 'featured_image'), extra=5) -
Django Admin Issue when Updating, Path must be fully qualified
I'm in the middle of upgrading a big Django project through each release to hopefully get up to 1.11. But I'm having issues getting to some of the pages. For instance, I'm not able to access the /admin/ panel. I'm having this issue currently on 1.8.18 and beyond. my urls file looks similar to this: from django.contrib import admin urlpatterns = [ ... url(r'^admin/', include(admin.site.urls)), #Tried this: # url(r'^admin/', admin.site.urls), ] Out spits a pretty unhelpful trace, resulting in: ImportError: Could not import 'public_private_controller'. The path must be fully qualified. As I understand, in future versions of django (beyond 1.9) string URLs are no longer allowed and URL function paths must be set similar to my commented out version in above code. But this is 1.8 and I'm not sure where my issue lives. I've yet to get good hints from the trace: Full stack trace: Internal Server Error: /admin/ Traceback (most recent call last): File "/Users/rob/src/dm_env/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/rob/src/dm_env/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 254, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "/Users/rob/src/dm_env/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/rob/src/dm_env/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/rob/src/dm_env/lib/python2.7/site-packages/django/contrib/admin/sites.py", … -
Django calculate distinct sum of many to many field in line items
I am trying to create an invoice system. An invoice can have multiple line items and each line item can have multiple taxes - some items can have 3 taxes, while some have only 2, while some are tax-free. I want to calculate the total taxes on the invoice model, but I also want to represent the total sum of different taxes. For example: Item 1 is $100 (with 15% VAT) and Item 2 is $100 (with 15% VAT and 10% CAT). I want to show the total taxes for the invoice - VAT: $30 ; CAT: $10) I have three models. This is invoice model class Invoice(models.Model): number = models.CharField(max_length=55) sub_total = models.DecimalField(max_digits...) taxes = models.DecimalField(...) final_total = models.DecimalField(...) This is invoice items model class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, related_name="invoiceitems") name = models.CharField(max_length=55) quantity = models.DecimalField(max_digits...) price = models.DecimalField(...) taxes = models.ManyToManyField(Tax, related_name="taxitems") final_total = models.DecimalField(...) This is the tax model class Tax(models.Model): name = models.CharField(max_length=55) rate = models.DecimalField(..) -
NoReverseMatch: Reverse for ''django.contrib.auth.views.password_reset_confirm''
I'm using Django 1.5.12 and I get this error and don't know how to solve it. Other 'NoReverseMatch' post didn't help me NoReverseMatch: Reverse for 'django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments '{u'iudb36': u'mg', u'token': u'4mb-cc37d48'}' not found. url.py urlpatterns = patterns('', (r'^my-account/password-reset/$', 'django.contrib.auth.views.password_reset', { 'post_reset_redirect': '/my-account/password-reset/done/', 'template_name': 'password_reset/password_reset_form.html', 'email_template_name': 'password_reset/password_reset_email.html' }), (r'^my-account/password-reset/done/$', 'django.contrib.auth.views.password_reset_done', { 'template_name': 'password_reset/password_reset_done.html' }), (r'^my-account/password-reset/((?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+))/$', 'django.contrib.auth.views.password_reset_confirm', { 'post_reset_redirect': '/my-account/password-reset/complete/', 'template_name': 'password_reset/password_reset_confirm.html' }) password_reset_email.html {% autoescape off %} You're receiving this e-mail because you requested a password reset for your user account. Please go to the following page and choose a new password: {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'django.contrib.auth.views.password_reset_confirm' uidb36=uid token=token %} {% endblock %} Any idea on how to solve this problem ? -
password encryption in django when importing users to USER model
I am trying to build an Api with an old database, which i am trying to move in USER model at Django. I configured table with Users for django USER model, however there is one problem. The passwords in old database are not encrypted, what means I can not log in with django. Any ideas how to solve this? Is there a way to encrypt the column of passwords or I can pass this in django? Any help would be very welcomed. Thank you. I am using sqlite3 -
Wagtail: How to add "Categories" to the Document model
One of the requirements for the project I'm working on at the moment is that pages can be associated with document libraries, and that each document uploaded to a library must be categorizable using a pre-defined set of categories (implemented using snippets, described in "Your First Wagtail Site" tutorial). Following this StackOverflow question about making a custom document object model, I used python manage.py startapp categorizeddocument, then defined a categorized document model as the following: from wagtail.wagtaildocs.models import AbstractDocument from django.db import models from django.db.models.signals import post_delete from modelcluster.fields import ParentalManyToManyField from django.dispatch import receiver from wagtail.wagtailsnippets.models import register_snippet from wagtail.wagtailadmin.edit_handlers import FieldPanel class CategorizedDocument(AbstractDocument): categories = ParentalManyToManyField('categorizeddocument.DocumentCategory', blank=True) admin_form_fields = ( 'title', 'file', 'collection', 'tags', 'category' ) @receiver(post_delete, sender=CategorizedDocument) def document_delete(sender, instance, **kwargs): instance.file.delete(False) @register_snippet class DocumentCategory(models.Model): name = models.CharField(max_length=255) panels = [ FieldPanel('name'), ] def __str__(self): return self.name class Meta: verbose_name_plural = 'document categories' I then added the categorizeddocument app to my INSTALLED_APPS and ran makemigrations and migrate, then set WAGTAILDOCS_DOCUMENT_MODEL = 'categorizeddocument.CategorizedDocument' However, I'm having some difficulty. My first problem is although the admin file picker panel renders okay, clicking to choose the file to upload never results in a file picker window. SO clearly I've done … -
Unable to Post data using Django REST Framework
I am gettting this error although I am giving proper string in Text and Title fields. I don't know what are the reasons. Serializer.py from rest_framework import serializers from blog.models import Post from django.utils import timezone from rest_framework.validators import UniqueValidator class blogSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('author','title', 'text','created_date','published_date') model.py from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User',null=True) title = models.CharField(max_length=200) text = models.CharField(max_length=200) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True,null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title views.py from blog.models import Post from .serializers import UserSerializer, GroupSerializer,blogSerializer from rest_framework import viewsets,status from rest_framework.decorators import api_view class blogViewSet(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = blogSerializer -
Groupby serializer in django REST
I am trying to write API endpoint which will take ?groupby=[field] as an argument and will pass it to CSV renderer. Problem is that my code looks little bit hacky. Are there better way to do this? Using filters maybe? class MyCSVRenderer(CSVRenderer): header = ['logged_at', 'chain_key', 'buyer', 'seller', 'amount'] class ChainsViewset(viewsets.ModelViewSet): serializer_class = ledger_serializers.ChainsSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = ChainFilter def get_queryset(self): return ledger_models.ChainLink.objects.all() @renderer_classes((MyCSVRenderer,)) def list(self, request, *args, **kwargs): groupby = self.request.query_params.get('groupby', None) queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) if groupby: queryset = queryset.values(groupby).annotate(amount=Sum('amount')) if queryset: MyCSVRenderer.header = queryset[0].keys() ChainsSerializer.Meta.fields = tuple(queryset[0].keys()) serializer = ChainsSerializer(queryset, many=True) return Response(serializer.data) else: MyCSVRenderer.header = ['logged_at', 'chain_key', 'buyer', 'seller', 'amount'] serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) renderer_classes = (BrowsableAPIRenderer, JSONRenderer, CSVRenderer) -
Passing variable with POST in django
Hi im trying to pass a name from a form to a view in django using POST. There are no errors in the execution but its passing nothing from the template and dont know if i doing something wrong here. Im starting with django so i can have newbie errors. If u need more information tell me pls. Views.py def crear_pdf(request): empresa_selec = "" form = EmpModelForm() if request.method == 'POST': form = EmpModelForm(data=request.POST) if form.is_valid(): empresa_selec = form.cleaned_data['nombre'] #"empresa_selec" that's the empty variable Models.py class Empresa_modelo(models.Model): nombre = models.CharField(max_length=100,blank=True,null=True) Forms.py class EmpModelForm(forms.ModelForm): class Meta: model = Empresa_modelo fields = ["nombre"] template.html <div class="container-fluid"> <form method="POST" enctype="multipart/form-data" action="{% url 'crear_pdf' %}">{% csrf_token %} <p>Empresa</p> <input type="text" name="empresa"> <br> <button type="submit">Subir</button> </form> <br> <a class="btn btn-primary" href="{% url 'crear_pdf' %}">Atras</a> </div> -
Serving local static files in development
I've recently adopted this method of serving our static and media files for our docker containers running a wagtail django site. Serving static and media files from S3 wagtail I've just realised that I'm going to need to change some things locally in order to be able to serve static files :-( I don't want to run the collectstatic command for local dev, as that's going to put a load of uneccessary wagtailadmin stuff into the static folder which will then be in the github repo. Does anyone know how I'd serve the wagtail admin files without running collectstatic? -
Suggestion-tags appear on click in input Django
Hello im using Django with Taggit(Selectize) and I would like to give users the option to click on "suggestion-tags" and that they appear in the input field. I wrote some JS its working in the console but not in the template. No tags appear in the input field but the given tags are saved and when the user reloads the page the tags are displayed in the Input field. JS: $('.tags_select a').click(function() { var valueText = $(this).text(); var input = $('#id_I_want'); oldInput = input.val(); $('#id_I_want').val(oldInput + " " + valueText); newInput = input.val(); $(input).text(newInput); return false; }); html: {% load widget_tweaks %} <p class="formItems"> {{ SetForm.I_want|add_class:"" }}</p> <div class="tags_select"> <span>Tags</span> <a href="#">Fun</a> <a href="#">Lala</a> <a href="#">Airline</a> </div> I also tried to do an ajax call but same thing saved and displayed in the console but not shown in template when clicked. It is a Django form. I think that is the problem or it has something to to with Taggit. Does anybody know how I can make the tags appear immediately when they are clicked? -
Django validate_unique method is not fired on model save event
I have Django 1.10 project and a simple model like this: class Contact(models.Model): user = models.ForeignKey(User) client_id = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'contact' def validate_unique(self, *args, **kwargs): if Contact.objects.filter(user = self.user, client_id = self.client_id).exists(): raise ValidationError('An attempt to save duplicate contact') super(Contact, self).validate_unique(*args, **kwargs) ...and a view: def test_unique_constraint(request): contact = Contact(name = 'Test', client_id = 111, user_id = 4) contact.save() # validate_unique is not called I am tearing my hair on my head trying to understand WHY VALIDATE_UNIQUE IS NOT BEING CALLED BEFORE SAVING contact instance !!! Help me please with this. -
Problems with editing multiupload image field
I have problem with editing form in django. Pls can someone help me? I have form with 2 fields: description and image. By this form users can edit currect article data. For example add new several images to article or update/delete one of the currect image. To create image field I used django-multiupload app. Also I load data to server by ajax. I tried next code but it didnt show me currect images in image field. Only descrtiption field works fine and show me currect data. How to fix this problem? models.py: class Article(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) description = models.TextField(_('Description')) class Image(models.Model): article= models.ForeignKey(Article, on_delete=models.CASCADE) image = models.FileField(_('Image'), upload_to='images/%Y/%m/%d/') forms.py: class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('description', ) image = MultiFileField() def save(self, commit=True): instance = super(ArticleForm, self).save(commit) return instance views.py: def article_edit(request, article_id): data = dict() article= get_object_or_404(Article, pk=article_id) if request.method == 'POST': article_form = ArticleForm(request.POST, request.FILES, instance=article) if article_form.is_valid(): article.save() data['form_is_valid'] = True articles = Article.objects.all context = {'articles': articles} context.update(csrf(request)) data['html_article'] = render_to_string('project/article_list.html', context) else: data['form_is_valid'] = False else: article_form = ArticleForm(instance=article) context = {'article_form': article_form} data['html_article_form'] = render_to_string('project/article_edit.html', context, request=request) return JsonResponse(data) -
Django handling request
I want to know if django creates a new instance of the view (or the whole app) on each request. Im not sure if this fit too but would love to know if a request will have to wait for a current one to complete before the incoming starts? Thanks in advance -
Django Ability to modify http_session from channel_session
i have an issue with Django channels. need to be able to view/modify http_session (request.session[]) from channel_session. I have tried lots of options and ended up with no solution or maybe am missing something in between. here is a code snippet of what i have and what i need to do. @channel_session_user def connectedChannel(message): print("Message Connected decrypting in Clients") encKey=MD5.new(str(message.reply_channel)).hexdigest() decryptedJSON=decrypt(b64decode(message['text']),encKey) messageJSON=json.loads(decryptedJSON) if messageJSON["target"] == 'login': Client = user.objects(lgnName=messageJSON['lgnName'],lgnPass=messageJSON['lgnPass'] ) if Client.count() == 1: redirectPage="/index.html?lgnName={}&lgnPass={}".format(messageJSON['lgnName'],messageJSON['lgnPass']) encryptedRedirectPage = b64encode(encrypt(redirectPage,encKey)) ''' ***Here I need to be able to set http_session somehow*** ''' message.reply_channel.send({ 'text':json.dumps({'verdict':encryptedRedirectPage}) }) else: #print "Client Not Accepted" redirectPage="False" encryptedRedirectPage = b64encode(encrypt(redirectPage,encKey)) message.reply_channel.send({ 'text':json.dumps({'verdict':encryptedRedirectPage}) }) -
How can I convert all SMALLINT columns in PostgreSQL database to BOOLEAN?
I migrated my Django website database from MySQL to PostgreSQL using a third party tool pgloader. But since MySQL stores BOOLEAN data as TINYINT by default(at least with Django), it got converted to SMALLINT in PostgreSQL. Now Django is showing error that smallint is being treated as boolean. Due to this, I want to convert all smallint columns to boolean. Is there a single command to convert all columns in all tables in a single database to required type? If I have to perform the operation separately for each table, that's OK too.