Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ForeignKey to multiple Models or Queryset

It is possible to make a ForeignKey to more than one model. I want to choose from different models like Parts and Machines Model.

I read this to combine multiple models into one list: How to combine 2 or more querysets in a Django view?

How can I get foreign key to that list somehow?

like image 707
Harry Avatar asked Jan 26 '11 10:01

Harry


People also ask

What is the difference between ForeignKey and OneToOneField?

The only difference between these two is that ForeignKey field consists of on_delete option along with a model's class because it's used for many-to-one relationships while on the other hand, the OneToOneField, only carries out a one-to-one relationship and requires only the model's class.

WHAT IS models ForeignKey?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.

How do I merge two Django models?

1 Answer. Show activity on this post. In your models Device and History models are related with a foreign key from History to DeviceModel, this mean when you have a History object you can retrieve the Device model related to it, and viceversa (if you have a Device you can get its History).

How are foreign keys used in models?

To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter. You also need to specify the name of the table which is going to participate in relationship. I mean to say, define the foreign key table.


2 Answers

I know that you asked this over year ago, but I had a similar problem and I want to share a link to the solution for future readers.

Generally the contenttypes framework solves this problem, and I guess this is what Daniel Roseman was talking about.

How to use dynamic foreignkey in Django?

like image 69
b3niup Avatar answered Oct 05 '22 22:10

b3niup


You need generic relations.

A generic relation allows you to dynamically the target model of the foreign key.

like image 39
Daniel Roseman Avatar answered Oct 05 '22 21:10

Daniel Roseman