Wednesday, 26 May 2021

How to create and serialize an unmanaged model Django

I've currently got existing tables in my database that were created with models as per the usual way (using makemigrations and migrate).

Now, I am looking to combine certain data from these existing tables, without having to create a new table in my database. Then, I would like to serialise that data to make it accessible via the views APIs.

My understanding is that I create an unmanaged model to handle this. I understand as part of the docs that you need to specify managed = False but that's just a start. So far, I've literally only found one link (that isn't very helpful): https://riptutorial.com/django/example/4020/a-basic-unmanaged-table-

Let's say hypothetically, I've got user information that is inputted in many different tables in my existing database and I'd like to create certain data points within my new and unmanaged model to combine it into one serialiser. As of now, this is what I've come up with. Note that in my user model, I don't know what to specify for my db_tables parameter since, like I mentioned, data will be coming from many different tables, not just one.

UserModel

from django.db import models

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

    class Meta:
        managed = False
        db_table = "Sample_Table_1"

UserSerializer

from rest_framework import serializers
from models.user import UserModel

class UserSerializer(serializer.ModelSerializer):
    class Meta:
        model = UserModel
        fields = "__all__"

UserViewSet

from rest_framewirk.viewsets import ModelViewSet 
from models.user import UserModel 
from serializers.user import UserSerializer

class UserViewSet(ModelViewSet):
    queryset = UserModel.objects.all()
    serializer_class = UserSerializer

    def list(self, request **kwargs):
        return super(UserViewSet, self).list(request)

Where do I go from here if I wanted to get another data point from a different table other than db_table = "Sample_Table_1"? For example, if I wanted data from a Sample_Table_2 table?

I think my main issue is that I don't really know how unmanaged models work and how I can retrieve data from different tables that already exist in my database. If anyone can point me to a tutorial that can help me with that, it would be a good start.



from How to create and serialize an unmanaged model Django

No comments:

Post a Comment