A
A
Alex Xmel2022-03-09 16:14:02
Django
Alex Xmel, 2022-03-09 16:14:02

How to create one ForeignKey for two tables at once?

There are two simple tables:

class WorkerMan(models.Model):
    name = models.CharField('Имя', max_length=20)
    age = models.PositiveSmallIntegerField('Возраст')

class WorkerWoman(models.Model):
    name = models.CharField('Имя', max_length=20)
    age = models.PositiveSmallIntegerField('Возраст')

it is necessary to create the third table ForeignKey which will be simultaneously on both tables. something like this:
class Director(models.Model):
    name = models.ForeignKey((WorkerMan, WorkerWoman), on_delete=models.DO_NOTHING)

Tell me how to implement it?
Of course, you can decide on the forehead: create another intermediate table into which to merge the first two and throw ForeignKey to it, but you don’t want to fence unnecessary tables. I'm sure it can be done in a simpler way.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2022-03-09
@bacon

remove WorkerMan and WorkerWoman and make it just Worker, gender is an attribute. Director with ForeignKey, also a dubious choice (although without TK, I can’t say for sure)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question