'Running SQL query in Django and improperly configure error
We have four tables Including Category, Seller, Product, Product_Seller. Each product has one category. each seller can sell a product. Suppose you do not sell the same product multiple times and each seller sells each product at most once. We want to find products that have more than 5 sellers. and we want to find the second category that has the largest number of products. I want to run the SQL code in Django. But it has multiple errors. Please let me know how can I fix it Using ORM. Thank you for your time and consideration.
from django.db import models
from django.db import connection
class Category(models.Model):
title = models.CharField(max_length=128)
class Seller(models.Model):
name = models.CharField(max_length=128)
product = models.ForeignKey(
Product,
on_delete=models.CASCADE,
related_name='Seller'
)
class Product(models.Model):
category_id = models.ForeignKey(
Category,
on_delete=models.CASCADE,
related_name='Product'),
rate = models.IntegerField(blank=True, null=True)
class ProductSeller(models.Model):
product_id = models.ForeignKey(product),
seller_id = models.ForeignKey(seller),
price = models.IntegerField(blank=True, null=True)
cursor = connection.cursor()
cursor.execute("""
SELECT product_id
FROM ProductSeller
GROUP BY product_id
HAVING COUNT(product_id) > 5
""")
cursor.execute("""
SELECT category_id
FROM Product
GROUP BY category_id
HAVING MAX(mycount)
FROM(SELECT category_id, Count(category_id) mycount
FROM orders
GROUP BY category_id)
AND NOT IN(SELECT category_id
FROM Product
GROUP BY category_id
HAVING MAX(mycount)
FROM(SELECT category_id, Count(category_id) mycount
FROM orders
GROUP BY category_id));
""")
the errors are:
---------------------------------------------------------------------------
ImproperlyConfigured Traceback (most recent call last)
<ipython-input-15-bdbc27a2a35a> in <module>
1 from django.db import models
2 from django.db import connection
----> 3 class Category(models.Model):
4 title = models.CharField(max_length=128)
5 class Seller(models.Model):
~/anaconda3/lib/python3.7/site-packages/django/db/models/base.py in __new__(cls, name, bases, attrs, **kwargs)
105
106 # Look for an application configuration to attach the model to.
--> 107 app_config = apps.get_containing_app_config(module)
108
109 if getattr(meta, 'app_label', None) is None:
~/anaconda3/lib/python3.7/site-packages/django/apps/registry.py in get_containing_app_config(self, object_name)
250 Return None if the object isn't in any registered app config.
251 """
--> 252 self.check_apps_ready()
253 candidates = []
254 for app_config in self.app_configs.values():
~/anaconda3/lib/python3.7/site-packages/django/apps/registry.py in check_apps_ready(self)
132 # INSTALLED_APPS raises a more helpful ImproperlyConfigured
133 # exception.
--> 134 settings.INSTALLED_APPS
135 raise AppRegistryNotReady("Apps aren't loaded yet.")
136
~/anaconda3/lib/python3.7/site-packages/django/conf/__init__.py in __getattr__(self, name)
74 """Return the value of a setting and cache it in self.__dict__."""
75 if self._wrapped is empty:
---> 76 self._setup(name)
77 val = getattr(self._wrapped, name)
78 self.__dict__[name] = val
~/anaconda3/lib/python3.7/site-packages/django/conf/__init__.py in _setup(self, name)
59 "You must either define the environment variable %s "
60 "or call settings.configure() before accessing settings."
---> 61 % (desc, ENVIRONMENT_VARIABLE))
62
63 self._wrapped = Settings(settings_module)
ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Solution 1:[1]
Try this:
from django.db import models
from django.db import connection
class Category(models.Model):
title = models.CharField(max_length=128)
class Seller(models.Model):
name = models.CharField(max_length=128)
class Product(models.Model):
category_id = models.ForeignKey(category),
rate = models.IntegerField(blank=True, null=True)
class Product_Seller(models.Model):
product_id = models.ForeignKey(product),
seller_id = models.ForeignKey(seller),
price = models.IntegerField(blank=True, null=True)
Here's an example query - but why not use the ORM? It is Django's killer feature! You'd likely have to change the table name below to be appname_product_seller, and it should be ProductSeller, not Product_Seller. Python's convention is CamelCase for Classes, and snake_case for functions, attributes, and variables.
cursor = connection.cursor()
cursor.execute("""
SELECT product_id
FROM Product_Seller
GROUP BY product_id
HAVING COUNT(product_id) > 5
""")
I'd recommend going through the Django tutorial if you haven't. It contains a lot of really good information.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | FlipperPA |
