Django Rest Framework & Entity–attribute–value model (EAV) Data Model

本秂侑毒 提交于 2019-12-06 01:34:46

I have faced the similar problem So I'll explain a little scenario here. So you can take reference from that.

Added some related names in models :

class Asset(models.Model):
    """
    Asset of EAV
    """
    asset = models.CharField(max_length=216, null=False,
                            default='asset', name='asset',
                            verbose_name='Asset of EAV'
                            )
    entity = models.ForeignKey(to=Entity, related_name='asset_entity')

class Value(models.Model):
    """
    Value of EAV
    """
    value = models.CharField(max_length=216,
                             null=False, default='value',
                             name='value', verbose_name='Value of EAV'
                             )
    asset = models.ForeignKey(to=Asset, related_name='asset_value')
    owner = models.ForeignKey(User, verbose_name='EAV Owner', related_name='eav')

initial queryset looks like this, the idea is to fetch all information that is required initially:

 queryset = Entity.objects.filter('**condition comes here**')
                .values('id', 'entity', 'asset_entity', 'asset_entity__asset', 'asset_entity__asset_value', 'asset_entity__asset_value__value',
                    'asset_entity__asset_value__owner_id',)

Pass this queryset when trying to make response :

serializer = serializer(queryset, many=True, context={'request': request})

Serailizers :

class Owner_Serializer(serializers.ModelSerializer)

        class Meta:
            model = User
            exclude = ('**exclude fields you want to exclude**', )


class EntitySerializer(serializers.Serializer):

        id = serializers.IntegerField(source='id')
        entity = serializers.CharField(source='entity')
        owner =  serializers.SerializerMethodField()
        groups =  serializers.SerializerMethodField()
        asset =  serializers.SerializerMethodField()


        def get_owner(self, obj):
            return Owner_Serializer(obj.get('asset_entity__asset_value__owner_id'), context=self.context).data

Same process goes for groups and asset fields.

in get_owner() we have entity object and from that object we can get owner_id , as we have already fetched related data initially.

So the main idea here to fetch all data initially and then serilaize that data according to your requirement.

Existing Nested Serailization do not support the response format you required.

Note : Initial querset is vry important , you may need to use prefetch related there because we are fetching data using reverse relationship. Also I didn't test the queryset so have to make sure that correct related_names are used to fetch related data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!