Foreignkey of two tables in Django

Asked

Viewed 404 times

0

Fala, Povo!

I have the following problem: I am developing a site for a store that also performs services.

Then I have the Shopping and Sales Table (Saleorbuy) and the Services Table (Service)

For Saleorbuy I created a table to store the items of the cart (Cartitem) that receives the id of the sale or purchase of the product and the quantity.

The point is that in the Services there is also the possibility of including products (such as those necessary for the execution of the service)

My question is this: Would there be any way in Django to put more than one table in Foreignkey? EX:

class CartItem(models.Model):
    opid = models.ForeignKey(SalesOrBuy or Service, null=True, on_delete=models.CASCADE)

At first I had thought about creating a new table but I think it’s counter-productive since this new table would be exactly the same thing as Cartitem only for services.

Then I thought to leave the field as an integer, create a Choice field and link via code.

but I wonder if there is already something in the framework itself something

1 answer

2


There is the possibility of a table containing more than one foreign key but not a single foreign key referencing more than one table, what you can do is create one more property (a foreign key)so you can put as many relationships as necessary.

A foreign key is a field, which points to the primary key of another table or the same table. That is, there is a relationship between pairs of two tables or a single table

class CartItem(models.Model):
    opid = models.ForeignKey(SalesOrBuy, null=True, on_delete=models.CASCADE)
    service = models.ForeignKey(Service, null=True, on_delete=models.CASCADE)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.