Django models one foreign key for many tables

So, I had a question that I wanted to create a single table with a foreign key for several other tables and use a different type field to indicate in which table the key should belong.

class Status(Models.model): request = models.ForeignKey("Request1", "Request2", "Request3") request_type = models.IntegerField() ...Some status related data class Request1(Models.model): ...Some data class Request2(Models.model): ...Some other data Class Request3(Models.model): ...different data 

My question is, is it possible to define such a foreign key? another solution i was thinking about is to define my model like this

 class Status(Models.model): request1 = models.ForeignKey("Request1") request2 = models.ForeignKey("Request2") request3 = models.ForeignKey("Request3") ...Some status related data class Request1(Models.model): ...Some data class Request2(Models.model): ...Some other data Class Request3(Models.model): ...different data 

But if I do it this way, can I define a constraint through django, which says that only one foreign key is allowed to have data, and the other two should be empty? or I will have to strictly set this restriction on the db side (I use postgres). I would like to tell django to do this when it creates db, so I don't need to remember every time someone recreates db.

Any input or advice is appreciated. I am not married to any of these ideas, so if there is another smart way to achieve the same effect, I should hear it. Thank you for your time.

Edit: I am using django 1.7.10

+8
source share
1 answer

You must use the contentypes framework in Django.

Here is an example for a generic relationship here: https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#generic-relations For your requirement, this might look something like this:

 from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class Status(models.Model): request_type = models.ForeignKey(ContentType) request_id = models.PositiveIntegerField() request = GenericForeignKey('request_type', 'request_id') 

Then you can do something like the following:

 status1 = Status(request=Request1("foo")) status1.save() status2 = Status(request=Request2("bar")) status2.save() status1.request // <Request1 "foo"> status2.request // <Request2 "bar"> 
+15
source

Source: https://habr.com/ru/post/1235223/


All Articles