[Django]-How to create and serialize an unmanaged model Django

3👍

If you want to combine data from different tables, you can try with a DB view.
and put an unmanaged model in front of it.
for example:

1) Create a model with managed=False
class UserModel(models.Model):
    user = models.CharField(db_column="user", max_length=255)

    class Meta:
        managed = False
        db_table = "sample_table_1"
2) run makemigrations

Inside the migration file create a DB view (assuming Postgres) with a RunSQL

class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='UserModel',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('user', models.CharField(db_column='user', max_length=255)),
            ],
            options={
                'db_table': 'sample_table_1',
                'managed': False,
            },
        ),
        migrations.RunSQL(
            sql="""
                CREATE OR REPLACE VIEW sample_table_1 AS
                SELECT id, username AS user FROM auth_user;
                # Here I used <username> as an example
                """,
            reverse_sql="""
                DROP VIEW IF EXISTS sample_table_1;
                """
        )
    ]

3) run migrate
4) create the serializer
class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserModel
        fields = '__all__'

useful links:
https://www.fusionbox.com/blog/detail/using-materialized-views-to-implement-efficient-reports-in-django/643/

https://schinckel.net/2020/03/03/postgres-view-from-django-queryset/

1👍

If one already has tables in the database one should generally use the inspectdb [Django docs] management command to generate atleast the basic structure of these tables as models, you might need to fix some things that Django is not able to infer properly. You would (after configuring the database settings properly) run the following command, which will atleast get you started on making the correct models:

python manage.py inspectdb

In general you should refer to the Integrating Django with a legacy database section of the documentation.

Moving further, you seem to haven’t set the proper table name for your model (since it exists already, it’s name might be different from what Django will generate), so if you want a manual fix, you would set the db_table [Django docs] attribute in the model’s Meta:

class UserDetails(models.model):
    user = models.CharField(db_column="LABEL", max_length=255)

    class Meta:
        managed = False
        db_table = '<YOUR_TABLE_NAME_HERE>'

1👍

if you want to return data from different model to a single api call one way to achieve this is to user serializers.Serializer

class TestClass(serializers.Serializer):
    table1 = serializers.IntegerField()
    ......

and you can use this class for serialization.

Leave a comment