Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django MySQL Raw
So I want to get data from my mysql database. I want to get the street, name,... All my database data. So I want to make a django-mysql-raw query but I don't get my data instead I get: Data object (1) Can anybody help me? So and this is my code if you need it: # Create your models here. class Data(models.Model): userid = models.AutoField(primary_key=True) name = models.CharField(max_length=100, blank=True, null=True) firstname = models.CharField(max_length=100, blank=True, null=True) age = models.IntegerField(blank=True, null=True) street = models.CharField(max_length=100, blank=True, null=True) country = models.CharField(max_length=100, blank=True, null=True) postcode = models.IntegerField(blank=True, null=True) print("\n\n\n-----------") for p in Data.objects.raw('SELECT userid FROM Data'): print(p) print("-----------\n\n\n")``` -
is it fine to name django apps with capital letters?
In django I named my app as "Home". I created a class named "images" inside models.py and make migrations thus I got table created in my database as "Home_images". but the problem arises when I tried to execute raw query on that table. query = "select * from Home_images" cursor.execute(query) string query gets converted into smaller letters so django couldn't find table named "Home_images". -
Installing mod_wsgi in windows throws error using pip
C:\Users\admon>pip install mod_wsgi Collecting mod_wsgi Using cached mod_wsgi-4.7.1.tar.gz (498 kB) Using legacy 'setup.py install' for mod-wsgi, since package 'wheel' is not installed. Installing collected packages: mod-wsgi Running setup.py install for mod-wsgi ... error ERROR: Command errored out with exit status 1: command: 'c:\users\admon\appdata\local\programs\python\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\admon\\AppData\\Local\\Temp\\pip-install-6eym66br\\mod-wsgi_1f52cc6d2c7e4894895a1e698895bdcb\\setup.py'"'"'; __file__='"'"'C:\\Users\\admon\\AppData\\Local\\Temp\\pip-install-6eym66br\\mod-wsgi_1f52cc6d2c7e4894895a1e698895bdcb\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\admon\AppData\Local\Temp\pip-record-08vnzxv4\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\admon\appdata\local\programs\python\python39\Include\mod-wsgi' cwd: C:\Users\admon\AppData\Local\Temp\pip-install-6eym66br\mod-wsgi_1f52cc6d2c7e4894895a1e698895bdcb\ Complete output (33 lines): c:\users\admon\appdata\local\programs\python\python39\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg) running install running build running build_py creating build creating build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\mod_wsgi copying src\__init__.py -> build\lib.win-amd64-3.9\mod_wsgi creating build\lib.win-amd64-3.9\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win-amd64-3.9\mod_wsgi\server copying src\server\environ.py -> build\lib.win-amd64-3.9\mod_wsgi\server copying src\server\__init__.py -> build\lib.win-amd64-3.9\mod_wsgi\server creating build\lib.win-amd64-3.9\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win-amd64-3.9\mod_wsgi\server\management creating build\lib.win-amd64-3.9\mod_wsgi\server\management\commands copying src\server\management\commands\runmodwsgi.py -> build\lib.win-amd64-3.9\mod_wsgi\server\management\commands copying src\server\management\commands\__init__.py -> build\lib.win-amd64-3.9\mod_wsgi\server\management\commands creating build\lib.win-amd64-3.9\mod_wsgi\docs copying docs\_build\html\__init__.py -> build\lib.win-amd64-3.9\mod_wsgi\docs creating build\lib.win-amd64-3.9\mod_wsgi\images copying images\__init__.py -> build\lib.win-amd64-3.9\mod_wsgi\images copying images\snake-whiskey.jpg -> build\lib.win-amd64-3.9\mod_wsgi\images running build_ext building 'mod_wsgi.server.mod_wsgi' extension creating build\temp.win-amd64-3.9 creating build\temp.win-amd64-3.9\Release creating build\temp.win-amd64-3.9\Release\src creating build\temp.win-amd64-3.9\Release\src\server C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\xampp\apache/include -Ic:\users\admon\appdata\local\programs\python\python39\include -Ic:\users\admon\appdata\local\programs\python\python39\include -IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE -IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE -IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt /Tcsrc/server\mod_wsgi.c /Fobuild\temp.win-amd64-3.9\Release\src/server\mod_wsgi.obj mod_wsgi.c c:\users\admon\appdata\local\temp\pip-install-6eym66br\mod-wsgi_1f52cc6d2c7e4894895a1e698895bdcb\src\server\wsgi_apache.h(39): fatal error C1083: Cannot open include file: 'ws2tcpip.h': No such file … -
Django Graphene how do i add custom fields to ObjectType of type model Object
class StoreType(DjangoObjectType): is_expired = graphene.Boolean(source='is_expired') is_pending = graphene.Boolean(source='is_pending') ranking = graphene.Int(source='ranking') success_rate = graphene.Float(source='success_rate') total_revenue = graphene.Float(source='total_revenue') best_selling_product = graphene.????(source='best_selling_product') class Meta: model = Store exclude = ['user'] for fields like is_expired, ranking etc.. i can easily see what type they are to be represented in e.g graphene.Int and graphene.Boolean, but the best_selling_product field is return Django object model.. here is the Model property below class Store(models.Model): .... def best_selling_product(self): products = self.orders.all().values_list('variant__product', flat=True) product_id = products.annotate(count=models.Count( 'variant__product')).order_by("-count")[0] return self.products.get(id=product_id) so what should i use to represent this and how? graphene.???? -
Django rest_framework datetime_format with milliseconds
Django REST_FRAMEWORK has a setting for the date format, e.g for timestamp in seconds: REST_FRAMEWORK = { 'DATETIME_FORMAT': '%s', } so my API output is for instance: {"creation_date":"1610700530"} How would I tell it to output a timestamp in milliseconds? E.g.: {"creation_date":"1610700530000"} -
Serializer not returning clean data in django-channels
I implemented serializer in my consumers.py to get data for a form I submit on the front end. But it doesn't seem to be returning ordered data. My consumers.py : import json from .models import Order from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from django.core import serializers from .serializers import OrderSerializer class WSConsumer(AsyncWebsocketConsumer): @database_sync_to_async def _get_order_info(self, number): j = Order.objects.get(order_number=number) response = OrderSerializer(instance=j).data return response async def connect(self): self.groupname = 'new_orders' await self.channel_layer.group_add( self.groupname, self.channel_name, ) await self.accept() async def disconnect(self, code): await self.channel_layer.group_discard( self.groupname, self.channel_name, ) await super().disconnect(code) async def take_order(self, event): number = event['number'] details = event['details'] info = await self._get_order_info(number) await self.send(text_data=json.dumps({ 'number' : number, 'details' : details, 'info' : info, })) async def receive(self, text_data): order_data_json = json.loads(text_data) number = order_data_json['number'] details = order_data_json['details'] info = order_data_json['info'] await self.channel_layer.group_send( self.groupname, { 'type': 'take_order', 'number' : number, 'details' : details, 'info' : info, } ) Here is what is returns in the console: {number: "50001", details: "fdgf", info: {…}} details: "fdgf" info: fulfilled_by: null id: 157 is_fulfilled: false order_date_time: "2021-01-15T10:37:46.200495Z" order_details: "fdgf" order_number: 50001 taken_by: 14 __proto__: Object number: "50001" __proto__: Object I feel it should return this: {number: "50001", details: "fdgf", info: fulfilled_by: null id: … -
How to return a response after django form is submitted?
I am new to django framework and application development. I am building an application to take some user input then process the data and save in the database. I am using Django forms to accept some input from user and send to my views. The data sent by user will be processed in the backend and then accordingly a response will be sent to the user after processing the data. I am able to successfully send the data from my template to the views. However, i am not getting how to send a response back to the template for user. Any suggestions on this would be very helpful. -
How to determine if someone exceeded the rate limit in Django Rest Framework in APIView? (throttling)
How to determine if someone exceeded the rate limit in Django Rest Framework in APIView? I need to log each case: logging.error("Request rate limit exceeded (throttling)" -
How to display user url avatar
i made a function that generates avatars for users when they create a profile: users/models.py def random_image(): directory = os.path.join(settings.BASE_DIR, 'media') files = os.listdir(directory) images = [file for file in files if os.path.isfile(os.path.join(directory, file))] rand = choice(images) return rand class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar_new = models.ImageField (default=random_image) def __str__(self): return f'{self.user.username} Profile' How can I now display this url img as a picture? -
Testing Django application with --parallel argument in Shippable
I have an application in django / python. I use Shippable to run my tests. In the shippable configuration file "shippable.yml", I use the following command: coverage run --source='.' manage.py test apps/ --parallel 2 But with that, Shippable displays a false coverage at just 23% But if I remove --parallel 2 like this: coverage run --source='.' manage.py test apps/ I get 58% Do you know how can I get the correct coverage using --parallel 2? -
How to test phonenumber_field.modelfields.PhoneNumberField
I am using django-phonenumber-field to store a phone number in my model. While covering the model with unit tests, raised a question of what would be an appropriate unit tests to test this field. The module itself is well tested and I should not retest this logic. But what shall I test instead? from phonenumber_field.modelfields import PhoneNumberField class User(models.Model): first_name = models.CharField(max_length = 50) phone_number = PhoneNumberField(null=False, blank=False, unique=True, help_text='Phone number') -
How to switch from MySQL to Postgre on Heroku
I want to host a django project on heroku. Locally, I developed it using MySQL database. And I have also pushed it to heroku but I get an Error message whenever I run heroku open command on command prompt. The error message is Can't connect to local MySQL server through socket. Though I'm a newbie in using databases, the way I understand the error is that heroku can't connect to local MySQL server which I'm using for local development. I don't want to connect to a remote MySQL database, instead, I want to connect to Postgre database just as heroku recommended. Being a newbie in the use of database, I don't know the best way to migrate to Postgre or how to add MySQL in my project to .gitignore. Is it possible for me to start running Postgre on heroku while MySQL isn't added to . gitignore and is still the database in settings.py? Must I clear MySQL database or add it to gitignore before I can use Postgre? -
Gitlab, How to have Multiple Project Folder in one repo, and only run unit test on merged project folder
I would like to create a Gitlab repo that have multiple projects accessing the same shared folder below are the details Repo of Project A Shared Folder project_folder 1 project_folder 2 project_folder 3 for each project_folders have it's own unit test when merge to git only runs it's own pipeline when deploy the whole project A gets deployed To be more specific, I have a django project, however as the project grows bigger, i would like to split the different sets of API into a project_folder of it's own However, each project_folder needs to refer to the same shared folder(django models, shared functionality code) So i would like to know if Git have a way to support this, and for each individual project_folder when i merge, gitlab will only run the unittest for the individual project_folder Thanks -
Why I obtain this error migrationg data from SQL Lite to Posgres DB ? duplicate key value violates unique constraint
I am pretty new in Django and Python and I am trying to follow this videotutorial about how to migrate a Django application from SqlLite to Postgres database: https://www.youtube.com/watch?v=ZgRkGfoy2nE&t=554s But I am finding some problem. Following the details on what I have done: I am working on Ubuntu 20.04 and I have a Django application made by someone else that uses SQLLite and that have to be migrated on Postgres. Following the previous tutorial I have done the following steps: First of all I installed Postegres and PgAdmin4 on my Ubuntu system. Then here I created a DB named dgsrgdb that have to be my new database for my application in replacement of SQL Lite DB. I installed this package to let Python\Django operate with Postgres: pip3 install psycopg2-binary I performed the backup of my original SqlLite DB by this command: python3 manage.py dumpdata > datadump.json and I obtained the datadump.json file that should contains the data inside the original DB that have to moved on the new Postgres DB. Into the Django settings.py file I replaced this configuration: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } whith this configuration related to Postgres: DATABASES = { … -
DataInput in Django forms
I would like to ask if it is possible in DataInput to set date display range only for given month I have already something like this in my files: forms.py class DataInput(forms.DateInput): input_type = 'date' class TimeInput(forms.TimeInput): input_type = 'time' class AvailabilityForm(forms.ModelForm): class Meta: model = Availability fields = ['user', 'date', 'starting_hour', 'ending_hour'] widgets = { 'date': DataInput(), 'starting_hour': TimeInput(), 'ending_hour': TimeInput() } I would just like the user to be able to select a day from the current month I would appreciate any advice -
Changing default Django site name and domain from example.com to the proper ones
According to the Django documentation (here): django.contrib.sites registers a post_migrate signal handler which creates a default site named example.com with the domain example.com. This site will also be created after Django creates the test database. To set the correct name and domain for your project, you can use a data migration. Isn't it safe to directly change the default values from the Django admin panel? why? -
Need a downgrade of Django on MacOS
I'm currently using Django version-3.1.5 but for my university course it's recommended for testing version-2.2.17. Was wondering how to downgrade using MacOS Terminal? When I use pip3 install Django-2.2.17 I get a error message saying I'm already on a newer version of Django. -
In Django, how to add username to a Model automatically, when the Form is submitted by a logged in user
In my Django app, I have defined a Many-to-one relationship using ForeignKey. Now what I want is that when a logged-in user submits the ListForm then his username should automatically add to the owner field of the ListModel. Currently when a user submits the form, None is being shown in the owner field, how I can add the username to the database along with the form? my models.py: from django.db import models from django.contrib.auth.models import User class ListModel(models.Model): owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) task = models.CharField(max_length=255) completed = models.BooleanField(default=False) my forms.py: from django.forms import ModelForm from .models import ListModel from django import forms class ListForm(ModelForm): class Meta: model = ListModel fields = ['task', 'completed'] -
Prefetch cannot resolve keyword with self through table
I have these model relations class Category(models.Model): categories = models.ManyToManyField( "self",symmetrical=False, through='ChildCategory', through_fields=('from_category', 'to_category')) level = models.IntegerField(default=1, db_index=True) description = models.CharField(max_length=100, blank=True, null=True) breadcrumb = models.CharField(max_length=255, blank=True, null=True) is_leaf = models.BooleanField(default=False) display_category = models.BooleanField(default=False) category_order = models.PositiveIntegerField(default=0, db_index=True) class Meta: default_related_name = 'categories' verbose_name = 'category' verbose_name_plural = 'categories' ordering = ['category_order'] def __str__(self): return self.description class ChildCategory(models.Model): from_category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='from_category') to_category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='to_category') category_order = models.PositiveIntegerField(default=0, db_index=True) class Meta: default_related_name = 'childcategories' ordering = ['category_order'] in context processor file i have this function from django.db.models import Prefetch from myapp.models import Category, ChildCategory def get_data(request): top_categories = Category.objects.prefetch_related( Prefetch('categories',queryset=ChildCategory.objects.select_related('from_category', 'to_category'),to_attr='children')).filter(level=1) print(top_categories.query) return { 'top_categories': top_categories, } but i get error Cannot resolve keyword 'category' into field How can i prefetch related child categories though the m2m ? -
why the django rest framework's search filter giving errors?
I am working on a demo DRF project to develop search and filter feature. However, I am not able to understand the issue with my project. I have some data stored in DB, and the GET is working fine. However, if I am doing some search operations in POSTMAN, I am seeing error, which is beyond my understanding. I have followed the below DRF official link. Below is the error raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: icontains [12/Jan/2021 11:32:53] "GET /api/shop/?search=Amitesh HTTP/1.1" 500 154116 Below are the project details: models.py from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.utils.translation import gettext_lazy as _ class AccountManager(BaseUserManager): def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('Enter the email before proceeding')) email = self.normalize_email(email) user = self.model(email=email, password=password, **extra_fields) user.set_password(password) user.save() return user class Shop(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) shop_name = models.CharField(max_length=150) contact = models.CharField(max_length=10) State = models.CharField(max_length=100) district = models.CharField(max_length=100) location = models.CharField(max_length=100) … -
Django -: adding multiple songs to playlist
i am creating the playlist to add songs in it....but i am unable to add multiple songs...i do not how to add. models.py---> from django.db import models from django.contrib.auth.models import User # Create your models here. class Song(models.Model): movie=models.CharField(max_length=200,blank=True) song_name=models.CharField(max_length=200) artist=models.CharField(max_length=200) year=models.IntegerField() image=models.ImageField(upload_to='images/') song_file=models.FileField(upload_to='songs/') def __str__(self): return self.song_name class Playlist(models.Model): list_name=models.CharField(max_length=100) user=models.ForeignKey(User,on_delete=models.CASCADE) song=models.ForeignKey(Song,on_delete=models.CASCADE,blank=True,default=None,null=True) def __str__(self): return self.list_name views.py ---> in this i have addsongs_view function through which i am trying to add the songs to the playlist but it is adding the only one song to the playlist and that one song is updated to all other playlists i.e. if am adding one song to playlist_1 ...that is also added to playlist_2 and rest others. **I want to add multiple songs to playlist and those songs should not add be added in other playlist if i am not adding it please help me thank you:) ** from django.shortcuts import render,redirect,get_object_or_404 from .models import Song,Playlist from django.contrib.auth.models import User # Create your views here. def home_view(request): songs=Song.objects return render(request,'home.html',{'songs':songs}) def allplaylists_view(request): playlists=Playlist.objects currentuser=request.user return render(request,'allplaylists.html',{'playlists':playlists, 'currentuser':currentuser}) def playlistsongs_view(request): playlists=Playlist.objects.all() playlistName=request.GET.get('name') return render(request,'playlistsongs.html',{'playlists':playlists, 'playlistName':playlistName}) def createplaylist_view(request): songs=Song.objects if request.method == 'POST': playlist=Playlist() playlist.list_name=request.POST['playlistname'] playlist.user=request.user playlist.save() print(playlist.list_name,playlist.user) return render(request,'addsongs.html',{'songs':songs}) else: return render(request,'createplaylist.html',{'songs':songs}) def … -
Django migration error : return self.cursor.execute(sql, params) django.db.utils.ProgrammingError:
I tried to delete the migrations folder and db.sqlite3 as suggestions but it didn't work. I've also tried to downgrade version of django. Please look at the error below, I think it's the problem with database : The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "c:\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Admin\Downloads\store2\Django-E-Commerce-master\user\models.py", line 8, in <module> from home.models import Language File "C:\Users\Admin\Downloads\store2\Django-E-Commerce-master\home\models.py", line 21, in <module> for rs in llist: File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\query.py", line 268, in __iter__ self._fetch_all() File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\query.py", line 54, in __iter__ results = … -
Serialize a get query in django-channels
I am trying to serialize a get queryset just as I did for filter below: from .models import Order from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from django.core import serializers class WSConsumer(AsyncWebsocketConsumer): @database_sync_to_async def _get_order_info(self, number): full_info = Order.objects.filter(order_number = number) data = serializers.serialize('json', list(full_info)) return data I keep getting certain errors, getting confused. I am trying to do something like: from .models import Order from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from django.core import serializers class WSConsumer(AsyncWebsocketConsumer): @database_sync_to_async def _get_order_info(self, number): full_info = Order.objects.get(order_number = number) data = serializers.serialize('json', list(full_info)) return data But it doesn't return a Queryset, so there are errors. How do I fix this? -
pylint with pylint-django doesnt throw errors for missing arguments
As far as I understood the function of pylint_django, not everything is possible due to the dynamic magic of Django, but missing arguments in "model fields" should be detected, right? I have this simple models class: from django.db import models class Product(models.Model): title = models.CharField() summary = models.TextField() CharField has a required argument max_length. Starting pylint: (project_venv) ➜ rorow pylint --load-plugins pylint_django --django-settings-module=rorow.settings products/models.py ************* Module products.models products/models.py:1:0: C0114: Missing module docstring (missing-module-docstring) products/models.py:2:0: C0115: Missing class docstring (missing-class-docstring) ------------------------------------------------------------------- Your code has been rated at 6.00/10 (previous run: 10.00/10, -4.00) Shouldn't the linter give an error here, like python manage.py runserver: ERRORS: products.Product.price: (fields.E130) DecimalFields must define a 'decimal_places' attribute. products.Product.price: (fields.E132) DecimalFields must define a 'max_digits' attribute. products.Product.title: (fields.E120) CharFields must define a 'max_length' attribute. -
Estoy iniciando en el python con django y tengo este problema: [closed]
Necesito buscar en una lista, pero necesito consultar en varias tablas o modelos que están relacionados. Un caso de ofidismo tiene lesionados (de la tabla Lesionados), ofídico (de la Tabla Ofidicos) y faboterápicos (de la tabla faboterá), además de sus campos específicos como Localización y Dosis de faboterápicos que se utilizaron en este caso específico. el código es este: def listar_ofidismos(request): busqueda = request.GET.get("buscar") post = Ofidismo.objects.all() if busqueda: post = Ofidismo.objects.filter( Q(Localización__icontains = busqueda) | Q(Dosis_Faboterápicos__icontains = busqueda) | Lesionado.objects.filter( Q(Nombres__icontains = busqueda) | Q(Apellidos__icontains = busqueda) ) | Ofidico.objects.filter( Q(Nombre_Cientifico__icontains = busqueda) | Q(Nombre_Popular__icontains = busqueda) | Q(Especie__icontains = busqueda) ) | Faboterapico.objects.filter( Q(Nombre_Comercial__icontains = busqueda) | Q(Nombre_Científico__icontains = busqueda) | Q(Compuestos__icontains = busqueda) ) ).distinct() print(post) paginator = Paginator(post,5) page = request.GET.get('page') post = paginator.get_page(page) return render(request, 'ofidismo_list.html', {'post':post}) No sé qué está mal, me dice algo del or, pero realmente no sé cómo formular esta consulta con varias tablas. Si alguien pudiera ayudarme! Please!! Gracias de antemano y saludos a todos los que están dispuestos a ayudar a la comunidad. Gracias!