from smartfarming.models.agriculture import KnowledgeCategory, KnowledgeManage, Information
from rest_framework import serializers
from smartfarming.models.user import DeviceUser


class KnowledgeCategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = KnowledgeCategory
        fields = "__all__"


class KnowledgeManageSerializer(serializers.ModelSerializer):
    category = serializers.SerializerMethodField()
    category_id = serializers.SerializerMethodField()
    is_top = serializers.SerializerMethodField()

    def get_is_top(self, obj):
        return True if obj.is_top else False

    def get_category(self, obj):
        try:
            category = KnowledgeCategory.objects.get(id=obj.category)
            return category.title
        except:
            return ""
    def get_category_id(self, obj):
        return obj.category

    class Meta:
        model = KnowledgeManage
        fields = [
            "id",
            "category",
            "title",
            "is_top",
            "related_plan",
            "addtime",
            "img",
            "origin",
            "content",
            "is_delete",
            "category_id"
        ]


class InformationSerializer(serializers.ModelSerializer):

    user = serializers.SerializerMethodField()

    def get_user(self, obj):
        return DeviceUser.objects.get(uid=obj.user).real_name

    class Meta:
        model = Information
        fields = "__all__"