Home > other >  Two projects use the same Postgres database, and the project on Django
Two projects use the same Postgres database, and the project on Django

Time:11-12

I have two projects that use the same Postgresql database. One of these projects is written with Golange and the other with Django. I have a task in the Django project, to take the data from the table that is created in another project. More precisely I have to take the data from the Clients table, which is not created in Django. There is no information about Clients table on the Django project.

Below is how I take the date from the Cook table, which is created in the Django project.

enter image description here

How can I take the date from the Clients table in the same way as above?

Below are both project repositories, and some screenshots from the database.

enter image description here

enter image description here

Thanks in advance.

CodePudding user response:

You have a couple of options:

  • Use Django's raw SQL queries to just SELECT data from that table
  • Use inspectdb to have Django generate a model for the clients table. The model will have Meta.managed set to False, so Django won't touch it (e.g. do migrations). You can then use regular Django ORM operations for it.
  • Manually write the model, setting db_table = "clients" and managed = False on the Meta class. You can then use regular Django ORM operations for it.

The model Django (or you) might generate could look something like

class Client(models.Model):
    id = models.IntegerField(primary_key=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    # ... etc ...

    class Meta:
       managed = False
       db_table = 'clients'

CodePudding user response:

Create Django models based on the database structure by introspecting an it with inspectdb command:

$ python manage.py inspectdb > models.py

Then you can query the database with Django API.

Have a look at https://docs.djangoproject.com/en/3.2/howto/legacy-databases/#auto-generate-the-models

  • Related