Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I upgrade heroku plan on Heroku?
I am going to upgrate plan on Heroku with my Django app from hobby-dev to hobby-basic. At the moment heroku pg:info returns: Plan: Hobby-dev Status: Available Connections: 0/20 PG Version: 9.6.4 Created: 2017-11-12 19:20 UTC Data Size: 135.9 MB Tables: 19 Rows: 1272760/10000 (Above limits, access disruption imminent) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql- ... I tried to use Upgrading Heroku Postgres Databases but I am not sure which way should I choose. It seems to be that pg:copy would be the best idea? I think that steps in this case should look as shown below, am I right? 1.heroku addons:create heroku-postgresql:standard-0 2.heroku pg:wait 3.heroku maintenance:on 4.heroku pg:copy DATABASE_URL HEROKU_POSTGRESQL_PINK --app sushi How can I check DATABASE_URL and HEROKU_POSTGRESQL_PINK? I quess that DATABASE_URL is in Config Vars and this is it postgres://gxapb...2840@ec2-77-131-196-1207.compute-1.amazonaws.com:5432/d...md, isn't it? But how can I generate HEROKU_POSTGRESQL_PINK? I found information that it is the target database. 5.heroku pg:promote HEROKU_POSTGRESQL_PINK 6.heroku maintenance:off -
Ajax + Django Like button
I have problems while I am building a simple like button. I have done everything as I have read in different tutorial but when I click on the Like button, it does not do anything. Look: models.py class Comentario (models.Model): titulo = models.CharField(max_length=50) texto = models.CharField(max_length=200) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) likes = models.IntegerField(default=0) views.py def like (request): com_id = None if request.method == 'GET': com_id = request.GET.get('comentario_id') likes = 0 if com_id: com = Comentario.objects.get(id=int(com_id)) if com: likes = com.likes + 1 com.likes = likes com.save() return HttpResponse(likes) urls.py urlpatterns = [ url(r'^like/$', login_required(views.like), name='like'), ] .html {% extends 'base/base.html' %} {% for comentario in objects %} ... {% if user.is_authenticated %} Like|{{ comentario.likes }} {% endif %} {% endfor %} js/ajax.js $('#likes').click(function(){ var comid; comid = $(this).attr("data-comid"); $.get('/home/like/', {comentario_id: comid}, function(data){ $('#like_count').html(data); $('#likes').hide(); }); }); And in base.html I have import all the .js base.html <script src="{% static 'jq/jquery-3.2.1.min.js' %}"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script> <script src= "{% static 'js/bootstrap.min.js' %}"></script> <script src= "{% static 'js/ajax.js' %}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> The issue is that when I push the button nothing happens. It is a simple code but somethin crashes. In the inspection do not show any error or … -
NoReverseMatch at / even after going back to the older working version
I did a reset master to this commit with hard-discard all working copy change, to the commit which was working perfectly. (and tried with much older commits as well) Also restarted the server. But still am not able to get rid of this error. Any help please! -
How can I connect Django with React?
I've got small application in React and several api on the server side. I want to deploy this site on Heroku. I performed the setup as stated on the site. As I started my project with react-start-app I ran npm run build Then python manage.py collectstatic Here is package.json { "name": "client", "version": "0.1.0", "private": true, "proxy": "http://127.0.0.1:8000", "dependencies": { "axios": "^0.16.2", "lodash": "^4.17.4", "materialize-css": "^0.100.2", "react-dom": "^15.6.1", "react-fileupload": "^2.4.0", "react-quill": "^1.0.0", "react-redux": "^5.0.6", "react-router-dom": "^4.2.2", "react-scripts": "1.0.12", "react-tabs": "^1.1.0", "redux": "^3.7.2", "redux-form": "^7.0.4", "redux-thunk": "^2.2.0" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" }, "devDependencies": { "eslint": "^4.5.0", "eslint-config-airbnb": "^15.1.0", "eslint-plugin-import": "^2.7.0", "eslint-plugin-jsx-a11y": "^5.1.1", "eslint-plugin-react": "^7.3.0", "react": "^15.6.1" } } settings.py ... STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') REACT_APP_DIR = os.path.join(BASE_DIR, 'client') STATICFILES_DIRS = [ os.path.join(REACT_APP_DIR, 'build', 'static'), ] And my entry point: views.py from django.views.generic import TemplateView class IndexView(TemplateView): template_name = 'index.html' 'index.html' is located in static dir, also I had en error and I changed with this configuration I ran heroku local web and opened http://0.0.0.0:5000 but there was clean page without any errors -
I have fixed select option list in HTML/CSS. I am trying to link it django char field.But Not finding a way through
Following is Django Form Field i have defined. source_currency = forms.CharField(max_length=5) Following is Select/Option HTML <select name="fancySelect" for="{{ form.source_currency.id_for_label }}" class="makeMeFancy" id="drop1"> <!-- Notice the HTML5 data attributes --> <option value="BTC" selected="selected" data-skip="1" data-icon="assets/images/large/bitcoin.png" data-html-text="BTC&lt;i&gt">BTC<span class="select_coin_button_arrow">▾</span></option> <option value="BTC" data-icon="assets/images/small/bitcoin.png" data-html-text="BTC&lt;i&gt" >BTC</option> <option value="ETH" data-icon="assets/images/small/ether.png" data-html-text="ETH&lt;i&gt;">ETH</option> How They can be linked so that on submit These values are passed as string? -
Failed system checks when hosting application
When I try to host my web app, I get this: (workout) sahands-mbp:workout sahandzarrinkoub$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10ce3b950> Traceback (most recent call last): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 405, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. workoutcal.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. workoutcal.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. System check identified 4 issues (0 silenced). I can't interpret this error message, because it doesn't look like a normal python error message. Before I got this error, I was … -
How to configure Django to run on MSSQL Server
I'm able to run Django 1.11 with SQLite Database. But I'm getting an error with MSSQL Server. Apart from settings.py file I had not modified anything. It is showing ImproperlyConfigured: Django 1.11 is not supported. Here is my configuration: Settings.py DATABASES = { 'default': { 'ENGINE': 'django_pyodbc', 'HOST': '127.0.0.1', 'NAME': 'demo2016', 'USER': 'sa', 'PASSWORD': '', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } In cmd prompt: C:\Users\Vitriv-Desktop\Desktop\sqldjango>python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 124, in … -
how to connect android studio to django for developing a android app with django backend
I have developed a website with django framework(simple website),but now i want to build a android app with django back end so can i use to android studio for front end and django for back end and if yes how to connect both for setting up development environment?? -
Using custom user model after having run migrate for the first time
In the documentation it says that if I want to override the default user model in a project, I need to do so before running any migrations or running manage.py migrate for the first time. I wonder what happens if I do the opposite, which is changing the user model to a custom one AFTER having run the migrations. I only have myself registered as a user to test the functionality of my web app, if I lose it, it doesn't matter to me. -
How can one display plain text obtained from a Validation Error?
Trying to display an error that was raised as part of a Validation sequence. But, the message being returned from the call, has HTML text that is a part of it. Would just like to have plain text available (with no HTML markups) Basically, the code that is being used is: forms.py def clean_username(self): username = self.cleaned_data.get('username') try: match = User.objects.get(username=username) except User.DoesNotExist: # Unable to find a user, this is what is wanted - so - just return the username return username # If a user was found with this as a username, raise an error. raise forms.ValidationError("This userid is already in use. Please supply a different userid.") views.py [.. snip ..] if user_form.is_valid() and profile_form.is_valid(): [... snip ...] registered = True message = 'Field employee has been registered' else: print(user_form.errors, profile_form.errors) message = str( user_form.errors ) + ' - ' + str( profile_form.errors ) <<<< message is being caught here else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'authorization/registration.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered, 'message': message}) on the template, this is what is displayed (in the case of a user already being in the DB) <ul class="errorlist"><li>username<ul class="errorlist"><li>This userid is already in use. Please supply a … -
Prepare Django app for tests with Postman
I'm working on a Django project that requires component tests using Postman. Usually I just use the tests that are available in the Django Rest Framework, but that is not sufficient for this project. I have all the tests working as they should, so that is not the problem here. The problem is that I have to prepare the data in the database manually every time the tests need to run. I have already created some helper functions that I can use to clear the database and enter the data again, but that still requires a manual action every time. Now I am looking for a way to automatically prepare the application for each test (suite) that needs to run. That way I could also use Jenkins or another CI framework. There are some requirements to the method that I would like to use: It must also be used by other testing frameworks (e.g. Cypress) It must be able to run automatically each time the tests are run I would like to use factory_boy as much as possible, but still have the ability to use fixed data. I have already thought of some ways that I could use: Create an … -
About capabilities and limitations of django relating to postgresql and deployment
I am currently developing an e-commerce website in django. As it is the first time that I am doing this, I should like to ask for some information regarding deployment in order to plan ahead. I am familiar with the general procedure for deploying to hosting services such as heroku, pythonanywhere, or AWS. I wanted to check, however, whether or not the specific database that I am using (postgresql) can be transferred to the remote postgres server that I will eventually use when I deploy my app, and if this is possible, how it is to be done? -
Running Django runserver doesn't respond on the browser
I've create a project in a server with CentOS, Django 1.10.1 and using python 3.5. When I run in the terminal py manage.py runserver 0.0.0.0:8000 it shows Performing system checks... System check identified no issues (0 silenced). December 10, 2017 - 15:45:23 Django version 1.10.1, using settings 'samplepy35.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. When I use the command netstat -tuplen it says that python is listening on PORT 8000. But when I try to access on the browser it doesn't respond. What can the problem be? -
Why doesn't DRF's serializer validate PositiveSmallIntegerField?
Using Django 1.11 and Django Rest Framework 3.7, I have a Person model class Person(models.Model): name = models.CharField(max_length=100) email = models.EmailField() age = models.PositiveSmallIntegerField() with a PersonSerializer class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ('id', 'name', 'age', 'email') and a ListCreate view class PersonList(generics.ListCreateAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer Using HTTPie, I can create a Person like this: $ http POST http://127.0.0.1:8000/api/people/ name=Alice age=26 email=alice@example.com HTTP/1.0 201 Created Allow: GET, POST, HEAD, OPTIONS Content-Length: 60 Content-Type: application/json Date: Sun, 10 Dec 2017 15:00:28 GMT Server: WSGIServer/0.1 Python/2.7.11 Vary: Accept, Cookie X-Frame-Options: SAMEORIGIN { "age": 26, "email": "alice@example.com", "id": 1, "name": "Alice" } When I create a Person with a bad email address, I get an error: $ http POST http://127.0.0.1:8000/api/people/ name=Bob age=33 email=oops HTTP/1.0 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Length: 42 Content-Type: application/json Date: Sun, 10 Dec 2017 15:01:08 GMT Server: WSGIServer/0.1 Python/2.7.11 Vary: Accept, Cookie X-Frame-Options: SAMEORIGIN { "email": [ "Enter a valid email address." ] } DRF knows it's an EmailField and automatically applies validation, so far so good. However, when I create a Person with a bad age (negative number), I get no error: $ http POST http://127.0.0.1:8000/api/people/ name=Charlie age=-10 email=charlie@example … -
Change the template and CBV depending on the nuber of results in queryset
I have a CBV that inherits from Listview. I need: If there is no element in the queryset, is empty, I need to show the template with a different message or another template If there is just one element in the queryset I need to go(redirect) to the DetailView Based on some previous answers that I received(on other questions) for 2, I think I need to overwrite get. If I I fully change get, my concern is that, later, if change change behavior, can create issue(it has also pagination, context related code). If I call super() and store get in a variable, how do I know/get the result of get_queryset ? -
Creating the object of a foreign or onetoone field from the model linked to it in the form?
Example model : class Profile(models.Model): user=models.OneToOnefield(User) name=models.Charfield() phone=models.IntegerField() Now in forms.py, I want to signup with all the above information. How can we nest the foreign or onetoone field so we can create user. -
django rest's viewset calls default serializer's create method instead of overriden method
I have a nested serializer with overridden create method: class OrderSerializer(serializers.ModelSerializer): data_model=Order user = UserSerializer(many=False) class Meta: model = Order fields = ['uid', 'user','price'] def create(self, validated_data): validated_data=validated_data.pop('user') order=self.data_model.objects.create(**validated_data) order.user=self.context['request'].user order.save() return order class LifeOrderSerializer(OrderSerializer): data_model =LifeOrder class Meta(OrderSerializer.Meta): model = LifeOrder fields = OrderSerializer.Meta.fields + [ "birth_year", "contract_duration",] and in the views.py class OrderViewSet(viewsets.ModelViewSet): queryset_model = LifeOrder serializer_class = LifeOrderSerializer def get_queryset(self): self.queryset_model.objects.all() but when I send a post request to create , model serializers defualt create method gets called! what is the problem? -
Django add recipe form
I'm Django newbie and I have some problem with my code. I hope you will give me some advice. So I can't save Recipe into my database through RecipeCreateForm. Here is my code: models.py class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='recipes_created') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, blank=True) image = models.ImageField(upload_to='recipes/%Y/%m/%d') description = models.TextField("Description") ingredients = models.TextField("Ingredients") preparation = models.TextField("Preparation") created = models.DateField(auto_now_add=True, db_index=True) def __str__(self): return self.title forms.py from django import forms from .models import Recipe class RecipeCreateForm(forms.ModelForm): class Meta: model = Recipe fields = ('title', 'image' 'description', 'ingredients', 'preparation') And how should look like views.py file? -
Django form sender is receiver
I'am creating simple contact form in Django for a website. It works fine, however, mail to a receiver is send from receiver and not from sender specified in a form. Consequently, receiver can not respond to a mail. I can try to paste a sender email to a message so receiver will know an address, but there must be more elegant way of doing that and I dont't know the way. -
How to play background video in Django form?
{% load staticfiles %} <!DOCTYPE html> <html> <head> <title style="font-weight:bold; font-family:cursive">Font Maker </title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <link href='ank1.css' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <div class="embed-responsive embed-responsive-4by3"> <body> <div class="page-header"> <h1><a href="/"style="font-weight:bold; font-family:cursive">FoNt MaKeR</a></h1> </div> <video autoplay loop muted="background"> <source src="//player.vimeo.com/external/158148793.hd.mp4?s=8e8741dbee251d5c35a759718d4b0976fbf38b6f&profile_id=119&oauth2_token_id=57447761"type="video/mp4"></source> </video> <div class="content container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> </div> </div> </div> </body> </div> </html> By this, video is playing but not in background of the page. Video is playing in another section but not in background. One more thing, I am not able to play video which is downloaded in my system. -
Django: allow multiple accounts for a single profile
I would like to enable multiple logins (credentials & permissions) for a single profile in my app. Here is my current code: from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Ideally, I'd like the User model to have a ForeignKey to Profile, and that would be it. I could then have several Users for a same profile, and my problem would be solved. Unfortunately I don't want to extend the User model because it's quite nasty, so I'd like to be able to put it in my Profile model. ManyToManyField would work, but then the Users could have several profiles and that is not possible. Do you have a clean, simple way to make some kind of "Reverse Foreign key" ? Best, -
Cannot modify a model field on save()
I'm a beginner with Django, and first time askig :) I'm following a simple tutorial on generating a slug for a string (let's say a slug for a blog post generated from its title). Perhaps I'm following an outdated guide, perhaps I'm missing a basic thing, I have no idea. Django 2.0 Python 3.6 I am trying to do a very simple task of slugifying a simple string, so: User enters a string in a simple form When hitting 'save', the title goes through slugify and creates the slug Save. models.py from django.db import models class Testmodel(models.Model): title = models.CharField(max_length=220) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.title views.py from django.views.generic.edit import CreateView class TestCreate(CreateView): model = Testmodel fields = '__all__' forms.py from django.forms import ModelForm from .models import Testmodel class TestCreateForm(ModelForm): class Meta: model = Testmodel fields = '__all__' Up until here everythig works, if I enter the slug manualy. In order to do it automaticaly, I have tried: Overriding the save() method withing my ModelForm class. Overriding the form_valid() method within the CreateView Overriding the save() method within the model itself. Tried to connect a pre_save signal to the model. In all of these 4 tries, I had … -
Django url with query params and single view to retrieve different set of objects
I have a model Book: class Book(models.Model): book_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) # A book can have multiple authors and an author can have multiple books author = models.ManyToManyField('Author') genre = models.CharField(max_length=20) isbn = models.CharField(max_length=20) summery = models.CharField(max_length=100, null=True) language = models.CharField(max_length=20, null=True) status = models.CharField(max_length=15, null=True) number_of_pages = models.IntegerField(blank=True) borrowed = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) loan_period = models.IntegerField(default=14) due_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) # A library has many books which_library = models.ForeignKey('Library', related_name='books', on_delete=models.CASCADE) #This helps to print in admin interface def __str__(self): return u"%s" % (self.title) I have one url that gives me all the books in a specific library: urlpatterns = [ url(r'^books/(?P<library_id>[0-9]+)$', book_list), ] My view that returns those book objects: @api_view(['GET', 'POST']) def book_list(request, library_id): """ List all books in a specific library, or create a new book for a specific library """ if request.method == 'GET': books = Book.objects.filter(which_library=library_id) print(books) serializer = BookSerializer(books, many=True) return Response(serializer.data) My question is: can I and if yes how can I modify my url and view so that this complete list of books can be filtered for different query params to return those specific books i.e. if I hit url such as api/books/1?genre=Fiction&status=Available should further filter … -
authenticating user and user groups django
iam a intermediate django developer who can create a simple blogs in django can anyone tell me is there any way to create django user groups where a user can create a group and add users (everything should be clientside not on the admin side) to that group and they can share (links,pdf,documents everything in the group "Note":this is not the actual question just to have a glance about my question) and the outsider cannot see the group's activities any kind of help is highly appreciated or if you feel like it is a typical question please suggest me some ideas to make this happen if you have any reference links it will be helpfull for me thanks in advance -
MySQL Explain statement showing conflict results
Hi, We have this SQL query which is taking more time, we tried to dig deep into it, when I do explain, it shows the below output Query: SELECT `product_product`.`product_description_id` FROM `ss_shopproduct` INNER JOIN `product_product` ON (`ss_shopproduct`.`product_id` = `product_product`.`id`) INNER JOIN `product_productdescription` ON (`product_product`.`product_description_id` = `product_productdescription`.`id`) WHERE (`ss_shopproduct`.`shop_id` = %s AND `product_product`.`reservation_info_id` = %s AND `product_productdescription`.`is_combo` = %s) EXPLAIN command: *************************** 1. row *************************** id: 1 select_type: SIMPLE table: product_product type: ref possible_keys: PRIMARY,product_product_65ff6ffd,idx_product_description_id_id,product_product_3801de99 key: product_product_3801de99 key_len: 5 ref: const rows: 271608 Extra: Using where *************************** 2. row *************************** id: 1 select_type: SIMPLE table: product_productdescription type: eq_ref possible_keys: PRIMARY key: PRIMARY key_len: 4 ref: bbdb.product_product.product_description_id rows: 1 Extra: Using where *************************** 3. row *************************** id: 1 select_type: SIMPLE table: ss_shopproduct type: ref possible_keys: idx_product_id key: idx_product_id key_len: 4 ref: bbdb.product_product.id rows: 2 Extra: Using where The problem is product_product table is retrieved with index product_product_3801de99 has cardinality of 56, but the rows scanned were 271608. I couldn't figure out, what causing that table to scan that many rows. I have checked that ss_shopproduct table doesn't have index on shop_id but it's showing it scanned 2 rows. The tables product_product, ss_shopproduct and product_productdescription have 1.2M, 2.5M, 0.5M rows respectively. The EXPLAIN …