Why do you need a separate product_to_category database table? - opencart

I've been looking at the Opencart database structure and basically, they have a product table, a category table, and then a table with 2 columns which links a product_id to a category_id.
What is the reasoning behind this? Would it not make things simpler to just include the category_id as a column in the product table?

Because a product can belong to more than one category and signifies a many-to-many relationship. It is part of the normalization process.

Related

How to get two player records from same player table in one row in a table visualisation?

I have a database table of sports matches which has two fields for player IDs: p1_id and p2_id. These fields both have foreign keys to a player table where there is an id and a name field.
I want to build a table visualisation in PowerBI that has both player names in a single row. I can't do this easily because I can only use one of the foreign key relationships at any one time. I've tried using USERELATIONSHIP but it looks like this can only be used within a CALCULATE function.
I'm sure there's a way to do this but it's beyond me! Thanks in advance.
Try with lookupvalue.
p1Name = LOOKUPVALUE(players[Name],players[pID], SELECTEDVALUE('Table'[p1]))
p2Name = LOOKUPVALUE(players[Name],players[pID], SELECTEDVALUE('Table'[p2]))
You can also check this video [Lookup multiple values in DAX]:
https://www.youtube.com/watch?v=SRnIH0pnF3o&ab_channel=SQLBI

Join two records from same model in django queryset

Been searching the web for a couple hours now looking for a solution but nothing quite fits what I am looking for.
I have one model (simplified):
class SimpleModel(Model):
name = CharField('Name', unique=True)
date = DateField()
amount = FloatField()
I have two dates; date_one and date_two.
I would like a single queryset with a row for each name in the Model, with each row showing:
{'name': name, 'date_one': date_one, 'date_two': date_two, 'amount_one': amount_one, 'amount_two': amount_two, 'change': amount_two - amount_one}
Reason being I would like to be able to find the rank of amount_one, amount_two, and change, using sort or filters on that single queryset.
I know I could create a list of dictionaries from two separate querysets then sort on that and get the ranks from the index values ...
but perhaps nievely I feel like there should be a DB solution using one queryset that would be faster.
union seemed promising but you cannot perform some simple operations like filter after that
I think I could perhaps split name into its own Model and generate queryset with related fields, but I'd prefer not to change the schema at this stage. Also, I only have access to sqlite.
appreciate any help!
Your current model forces you to have ONE name associated with ONE date and ONE amount. Because name is unique=True, you literally cannot have two dates associated with the same name
So if you want to be able to have several dates/amounts associated with a name, there are several ways to proceed
Idea 1: If there will only be 2 dates and 2 amounts, simply add a second date field and a second amount field
Idea 2: If there can be an infinite number of days and amounts, you'll have to change your model to reflect it, by having :
A model for your names
A model for your days and amounts, with a foreign key to your names
Idea 3: You could keep the same model and simply remove the unique constraint, but that's a recipe for mistakes
Based on your choice, you'll then have several ways of querying what you need. It depends on your final model structure. The best way to go would be to create custom model methods that query the 2 dates/amount, format an array and return it

How to limit prefetch_related data in django

I've two tables brand and a product. each brand has multiple products.
So. I used prefetch_related to get related products for a particular brand with only a minimum product price. but the problem is when I have 2 products with the same price it selects both records so how to limit this?
alternatives_data = Brand.objects.filter(category__category_slug = category_slug).prefetch_related(
Prefetch('products', queryset=Product.objects.annotate(
min_brand_price=Min('brand__products__product_price')
).filter(
product_price=F('min_brand_price')
).order_by('product_id')))
i tried everything but nothing work!
To prevent a query to return multiple records with duplicata in specific columns, use the distinct method.
In your case, add .distinct('price') to the Product queryset inside the prefetch.
There is however one caveat : It is supported on PostgreSQL only.
Documentation

Django - joining multiple tables (models) and filtering out based on their attribute

I'm new to django and ORM in general, and so have trouble coming up with query which would join multiple tables.
I have 4 Models that need joining - Category, SubCategory, Product and Packaging, example values would be:
Category: 'male'
SubCategory: 'shoes'
Product: 'nikeXYZ'
Packaging: 'size_36: 1'
Each of the Model have FK to the model above (ie. SubCategory has field category etc).
My question is - how can I filter Product given a Category (e.g. male) and only show products which have Packaging attribute available set to True? Obviously I want to minimise the hits on my database (ideally do it with 1 SQL query).
I could do something along these lines:
available = Product.objects.filter(packaging__available=True)
subcategories = SubCategory.objects.filter(category_id=<id_of_male>)
products = available.filter(subcategory_id__in=subcategories)
but then that requires 2 hits on database at least (available, subcategories) I think. Is there a way to do it in one go?
try this:
lookup = {'packaging_available': True, 'subcategory__category_id__in': ['ids of males']}
product_objs = Product.objects.filter(**lookup)
Try to read:
this
You can query with _set, multi __ (to link models by FK) or create list ids
I think this should work but it's not tested:
Product.objects.filter(packaging__available=True,subcategori‌​es__category_id__in=‌​[id_of_male])
it isn't tested but I think that subcategories should be plural (related_name), if you didn't set related_name, then subcategory__set instead od subcategories should work.
Probably subcategori‌​es__category_id__in=‌​[id_of_male] can be switched to .._id=id_of_male.

How to insert foreign key value into table

I want to insert the product in the product table but the product table is also having a category Id which is the foreign key ,How will I insert the foreign key through code please tell me.
i have used this syntax
NewItemToInsert.tbl_PRODUCT_CATEGORY.category_id = Convert.ToInt32 (categoryId);
Categories are displayed in the dropdown list on the add product page and to bind that dropdown I have written a class.
Category Id which I want to insert already exists in the Category table and that Id I want to add into Product table
Please give me useful suggesstions
Thanks
Ritz
you need to have the category table in memory (or use a proper enum that is in sync with the values in the db), and set the right categoryid when you do the update / insert command.
if you post the code, we can see if there is any problem there.
CategoryId you want to insert in Product table, should already exist in ProductCategory table.