Общие модели между двумя проектами и ForeignKey к неиспользуемой модели, существующей только в одном из них

I have two Django projects that communicate with each other. The first one contains model A and B that has a ForeignKey to A. The first project sends and receives serialized B objects from the second project. I want the second project to contain just B, but it needs the value of that ForeignKey. These models are defined as follows:

class A(models.Model):
    ...

class B(models.Model):
    fk = models.ForeignKey(to='A', on_delete=models.PROTECT)
    ...

The problem is that ForeignKey to A in model B requires model A to be defined in the second project. Its objects also have to exist so that the database is consistent and there are no problems, e.g., in the admin panel.

In the end, I'd like to treat the fk field as a full-fledged ForeignKey in the first project and as some kind of read-only generic identifier in the second one. I would like to have the same code base for the model in both projects to ensure databases in the two projects stay synchronized. How can I achieve this in a clean way?

В частности, мне нужно сохранить функциональность запросов в обоих направлениях в первом проекте, например, fk__some_a_field и b_set.

Если вы хотите использовать django orm, вам придется воссоздать вашу модель A из проекта 1 в проекте 2. Но так как модель A управляется проектом 1, подумайте о добавлении следующих строк к вашей модели в проекте 2:

class A(models.Model):
    ...
    
    class Meta:
        managed = False
        db_table = 'your database table name where A model is stored'

managed=False скажет django игнорировать миграции для нее, и django не будет позволено изменять таблицу базы данных этой модели.

Другое решение, если вы не хотите дублировать модели из проекта 1 в проект 2, это не использовать django orm. И писать sql запросы самостоятельно. Но, как вы упомянули, вы не хотите этого делать

P.S если вы не знаете, как посмотреть имя таблицы базы данных для модели A, вы можете вывести его следующим образом: a_model_instance._meta.db_table, или посмотреть его в некоторых инструментах, таких как pgadming, если вы используете postgres

Вернуться на верх