Пример #1
0
class UserObjectiveSerializer(InCasestudySerializerMixin,
                              serializers.ModelSerializer):
    parent_lookup_kwargs = {'casestudy_pk': 'aim__casestudy__id'}
    aim = IDRelatedField()
    user = IDRelatedField()
    keyflow = serializers.IntegerField(source='aim.keyflow.id',
                                       allow_null=True,
                                       read_only=True)

    #flow_targets = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = UserObjective
        extra_kwargs = {
            'target_areas': {
                'required': False,
                'allow_empty': True
            }
        }
        fields = (
            'id',
            'aim',
            'user',
            'priority',
            'keyflow',
            'target_areas',
            #'flow_targets'
        )
Пример #2
0
class ActorSerializer(DynamicFieldsModelSerializerMixin,
                      CreateWithUserInCasestudyMixin,
                      NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {
        'casestudy_pk': 'activity__activitygroup__keyflow__casestudy__id',
        'keyflow_pk': 'activity__activitygroup__keyflow__id',
    }
    activity = IDRelatedField()
    activity_name = serializers.CharField(source='activity.name',
                                          read_only=True)
    activitygroup_name = serializers.CharField(
        source='activity.activitygroup.name', read_only=True)
    activitygroup = serializers.IntegerField(
        source="activity.activitygroup.id", read_only=True)
    address = serializers.CharField(source='administrative_location.address',
                                    read_only=True)
    city = serializers.CharField(source='administrative_location.city',
                                 read_only=True)
    activity_url = ActivityField(view_name='activity-detail',
                                 source='activity',
                                 read_only=True)
    nace = serializers.CharField(source='activity.nace', read_only=True)

    website = URLFieldWithoutProtocol(required=False,
                                      default="",
                                      allow_blank=True)
    reason = IDRelatedField(allow_null=True)
    flow_count = serializers.IntegerField(read_only=True)

    class Meta:
        model = Actor
        fields = ('url', 'id', 'BvDid', 'name', 'consCode', 'year', 'turnover',
                  'employees', 'BvDii', 'website', 'activity', 'activity_url',
                  'activity_name', 'activitygroup', 'activitygroup_name',
                  'included', 'nace', 'city', 'address', 'reason',
                  'description', 'flow_count')
        extra_kwargs = {
            'year': {
                'allow_null': True
            },
            'turnover': {
                'allow_null': True
            },
            'employees': {
                'allow_null': True
            }
        }

    # normally you can't upload empty strings for number fields, but we want to
    # allow some of them to be blank -> set to None when receiving empty string
    def to_internal_value(self, data):
        allow_blank_numbers = ['year', 'turnover', 'employees']
        for field in allow_blank_numbers:
            if (field in data and data[field] == ''):
                data[field] = None
        return super().to_internal_value(data)
Пример #3
0
class ChallengeSerializer(NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {'casestudy_pk': 'casestudy__id'}
    casestudy = IDRelatedField()
    keyflow = IDRelatedField(allow_null=True)
    text = serializers.CharField()

    class Meta:
        model = Challenge
        fields = ('url', 'id', 'casestudy', 'keyflow', 'text', 'priority',
                  'description')
Пример #4
0
class Group2GroupSerializer(FlowSerializer):
    origin = IDRelatedField()
    origin_url = ActivityGroupField(view_name='activitygroup-detail',
                                    source='origin',
                                    read_only=True)
    destination = IDRelatedField()
    destination_url = ActivityGroupField(view_name='activitygroup-detail',
                                         source='destination',
                                         read_only=True)

    class Meta(FlowSerializer.Meta):
        model = Group2Group
        fields = ('id', 'amount', 'keyflow', 'origin', 'origin_url',
                  'destination', 'destination_url', 'composition',
                  'description', 'year', 'publication', 'waste', 'process')
Пример #5
0
class Actor2ActorSerializer(FlowSerializer):
    origin = IDRelatedField()
    #origin_url = ActorField(view_name='actor-detail',
    #source='origin',
    #read_only=True)
    destination = IDRelatedField()

    #destination_url = ActorField(view_name='actor-detail',
    #source='destination',
    #read_only=True)

    class Meta(FlowSerializer.Meta):
        model = Actor2Actor
        fields = ('id', 'amount', 'composition', 'origin', 'destination',
                  'description', 'year', 'publication', 'waste', 'process')
Пример #6
0
class AreaOfProtectionSerializer(NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {'sustainability_pk': 'sustainability_field__id'}
    name = serializers.CharField()
    sustainability_field = IDRelatedField()

    class Meta:
        model = AreaOfProtection
        fields = ('url', 'id', 'name', 'sustainability_field')
Пример #7
0
class ImpactCategoryInSustainabilitySerializer(NestedHyperlinkedModelSerializer
                                               ):
    parent_lookup_kwargs = {'sustainability_pk': 'sustainability_field__id'}
    impact_category = IDRelatedField()

    class Meta:
        model = ImpactCategory
        fields = ('url', 'id', 'impact_category')
Пример #8
0
class MaterialSerializer(KeyflowInCasestudyDetailCreateMixin,
                         AllMaterialSerializer):
    # keyflow filtering is done by "get_queryset"
    parent_lookup_kwargs = {}
    keyflow = IDRelatedField(read_only=True)

    class Meta:
        model = Material
        fields = ('id', 'name', 'level', 'parent', 'keyflow', 'flow_count')
Пример #9
0
class FlowSerializer(CompositionMixin, NestedHyperlinkedModelSerializer):
    """Abstract Base Class for a Flow Serializer"""
    parent_lookup_kwargs = {
        'casestudy_pk': 'keyflow__casestudy__id',
        'keyflow_pk': 'keyflow__id',
    }
    keyflow = KeyflowInCasestudyField(view_name='keyflowincasestudy-detail',
                                      read_only=True)
    publication = IDRelatedField(allow_null=True, required=False)
    process = IDRelatedField(allow_null=True)
    composition = CompositionSerializer()

    class Meta:
        model = Flow
        fields = ('id', 'amount', 'keyflow', 'origin', 'origin_url',
                  'destination', 'destination_url', 'origin_level',
                  'destination_level', 'composition', 'description', 'year',
                  'publication', 'waste', 'process')
Пример #10
0
class AimPostSerializer(InCasestudySerializerMixin,
                        NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {'casestudy_pk': 'casestudy__id'}
    text = serializers.CharField()
    keyflow = IDRelatedField(allow_null=True, required=False)

    class Meta:
        model = Aim
        fields = ('url', 'id', 'keyflow', 'text', 'priority', 'description')
Пример #11
0
class FlowTargetSerializer(NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {
        'casestudy_pk': 'userobjective__aim__casestudy__id',
        'userobjective_pk': 'userobjective__id'
    }
    indicator = IDRelatedField()
    target_value = IDRelatedField()
    user = IDRelatedField(source='userobjective.user.id',
                          allow_null=True,
                          read_only=True)
    keyflow = IDRelatedField(source='userobjective.aim.keyflow.id',
                             allow_null=True,
                             read_only=True)

    class Meta:
        model = FlowTarget
        fields = ('id', 'indicator', 'target_value', 'user', 'keyflow',
                  'notes')
Пример #12
0
class PossibleImplementationAreaSerializer(SolutionDetailCreateMixin,
                                           NestedHyperlinkedModelSerializer):
    solution = IDRelatedField(read_only=True)
    edit_mask = serializers.ReadOnlyField()
    affected_actors = serializers.SerializerMethodField()
    parent_lookup_kwargs = {
        'casestudy_pk': 'solution__solution_category__keyflow__casestudy__id',
        'keyflow_pk': 'solution__solution_category__keyflow__id',
        'solution_pk': 'solution__id'
    }

    class Meta:
        model = PossibleImplementationArea
        fields = ('url', 'id', 'solution', 'question', 'geom', 'edit_mask',
                  'affected_actors')

    def create(self, validated_data):
        instance = super().create(validated_data)
        return self.makevalid(instance)

    def update(self, instance, validated_data):
        instance = super().update(instance, validated_data)
        return self.makevalid(instance)

    def makevalid(self, instance):
        if not instance.geom.valid:
            qs = PossibleImplementationArea.objects.filter(id=instance.id)
            qs.update(geom=CollectionExtract(MakeValid('geom'), 3))
            instance = qs[0]
        return instance

    def get_affected_actors(self, obj):
        parts = obj.solution.solution_parts
        #references = parts.values_list('flow_reference', flat=True)
        #changes = parts.values_list('flow_changes', flat=True)
        #flow_references = FlowReference.objects.filter(
        #id__in=list(references) + list(changes))
        #flow_references.filter(Q(origin_area=obj) | Q(destination_area=obj))

        # should be a sufficient filter because the area is solution specific
        flow_references = FlowReference.objects.filter(
            Q(origin_area=obj) | Q(destination_area=obj))
        affected_actors = []
        for flow_reference in flow_references:
            for area, activity in [(flow_reference.origin_area,
                                    flow_reference.origin_activity),
                                   (flow_reference.destination_area,
                                    flow_reference.destination_activity)]:
                if area != obj:
                    continue
                actors = Actor.objects.filter(activity=activity)
                actors = actors.filter(
                    administrative_location__geom__intersects=obj.geom)
                affected_actors.extend(actors.values_list('id', flat=True))
        affected_actors = set(affected_actors)
        return affected_actors
Пример #13
0
class ChartSerializer(ModelSerializer):
    parent_lookup_kwargs = {
        'casestudy_pk': 'chart_category__casestudy__id',
        'chartcategory_pk': 'chart_category__id',
    }
    chart_category = IDRelatedField(read_only=True)

    class Meta:
        model = Chart
        fields = ('id', 'name', 'image', 'chart_category')
Пример #14
0
class KeyflowInCasestudySerializer(NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {'casestudy_pk': 'casestudy__id'}
    note = serializers.CharField(required=False, allow_blank=True)
    casestudy = IDRelatedField()
    keyflow = IDRelatedField()
    groupstock_set = InKeyflowSetField(view_name='groupstock-list')
    group2group_set = InKeyflowSetField(view_name='group2group-list')
    activitystock_set = InKeyflowSetField(view_name='activitystock-list')
    activity2activity_set = InKeyflowSetField(
        view_name='activity2activity-list')
    actorstock_set = InKeyflowSetField(view_name='actorstock-list')
    actor2actor_set = InKeyflowSetField(view_name='actor2actor-list')

    activitygroups = InCasestudyKeyflowListField(
        view_name='activitygroup-list')
    activities = InCasestudyKeyflowListField(view_name='activity-list')
    actors = InCasestudyKeyflowListField(view_name='actor-list')
    administrative_locations = InCasestudyKeyflowListField(
        view_name='administrativelocation-list')
    operational_locations = InCasestudyKeyflowListField(
        view_name='operationallocation-list')

    code = serializers.CharField(source='keyflow.code',
                                 allow_blank=True,
                                 required=False)
    name = serializers.CharField(source='keyflow.name',
                                 allow_blank=True,
                                 required=False)
    graph_date = serializers.SerializerMethodField()

    class Meta:
        model = KeyflowInCasestudy
        fields = ('url', 'id', 'keyflow', 'casestudy', 'note',
                  'groupstock_set', 'group2group_set', 'activitystock_set',
                  'activity2activity_set', 'actorstock_set', 'actor2actor_set',
                  'code', 'note', 'name', 'activitygroups', 'activities',
                  'actors', 'administrative_locations',
                  'operational_locations', 'graph_date',
                  'sustainability_statusquo', 'sustainability_conclusions')

    def get_graph_date(self, obj):
        kfgraph = BaseGraph(obj)
        return kfgraph.date
Пример #15
0
class ImpactCategorySerializer(NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {}
    name = serializers.CharField()
    area_of_protection = IDRelatedField()
    spatial_differentiation = serializers.BooleanField()

    class Meta:
        model = ImpactCategory
        fields = ('url', 'id', 'name', 'area_of_protection',
                  'spatial_differentiation')
Пример #16
0
class AllMaterialSerializer(serializers.ModelSerializer):
    #keyflow = IDRelatedField(allow_null=True)
    parent = IDRelatedField(allow_null=True)
    level = serializers.IntegerField(required=False, default=0)
    flow_count = serializers.IntegerField(read_only=True)

    class Meta:
        model = Material
        fields = ('url', 'id', 'name', 'keyflow', 'level', 'parent',
                  'flow_count')
Пример #17
0
class SolutionSerializer(CreateWithUserInCasestudyMixin,
                         NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {
        'casestudy_pk': 'solution_category__keyflow__casestudy__id',
        'keyflow_pk': 'solution_category__keyflow__id'
    }

    solution_category = IDRelatedField()
    currentstate_image = serializers.ImageField(required=False,
                                                allow_null=True)
    activities_image = serializers.ImageField(required=False, allow_null=True)
    effect_image = serializers.ImageField(required=False, allow_null=True)
    implementation_count = serializers.SerializerMethodField()
    affected_activities = serializers.SerializerMethodField()

    class Meta:
        model = Solution
        fields = ('url', 'id', 'name', 'description', 'documentation',
                  'solution_category', 'activities_image',
                  'currentstate_image', 'effect_image', 'implementation_count',
                  'affected_activities')
        read_only_fields = (
            'url',
            'id',
        )
        extra_kwargs = {
            'description': {
                'required': False
            },
            'documentation': {
                'required': False
            },
        }

    def get_implementation_count(self, obj):
        return obj.strategy_set.count()

    def get_affected_activities(self, obj):
        parts = SolutionPart.objects.filter(solution=obj)
        activities = parts.values_list(
            'flow_reference__origin_activity__id',
            'flow_reference__destination_activity__id',
            'flow_changes__origin_activity__id',
            'flow_changes__destination_activity__id',
            'affected_flows__destination_activity__id',
            'affected_flows__origin_activity__id')
        activities = set([i for s in activities for i in s])
        try:
            activities.remove(None)
        except:
            pass
        return activities
Пример #18
0
class ProductFractionSerializer(serializers.ModelSerializer):
    publication = IDRelatedField(allow_null=True, required=False)
    id = serializers.IntegerField(label='ID',
                                  read_only=False,
                                  required=False,
                                  allow_null=True)
    parent_lookup_kwargs = {}

    class Meta:
        model = ProductFraction
        fields = ('id', 'composition', 'material', 'fraction', 'publication',
                  'avoidable', 'hazardous')
        read_only_fields = ['composition']
Пример #19
0
class LayerSerializer(serializers.ModelSerializer):
    lookup_url_kwarg = 'layercategory_pk'
    parent_lookup_kwargs = {'casestudy_pk': 'category__casestudy__id',
                            'layercategory_pk': 'category__id'}
    category = IDRelatedField(read_only=True)
    style = IDRelatedField(allow_null=True)
    order = serializers.IntegerField(required=False, default=None)
    proxy_uri = serializers.SerializerMethodField()
    legend_proxy_uri = serializers.SerializerMethodField()
    #wmsresource_uri = serializers.CharField(source="wms_layer.wmsresource.uri")

    class Meta:
        model = Layer
        fields = ('id', 'name', 'included', 'wms_layer', 'category', 'order',
                  'style', 'legend_uri', 'proxy_uri', 'legend_proxy_uri')
        #, 'wmsresource_uri')

    def get_proxy_uri(self, obj):
        return reverse('wms_proxy', args=(obj.id, ))

    def get_legend_proxy_uri(self, obj):
        uri = obj.legend_uri
        if not uri:
            return ''
        split = obj.legend_uri.split('?')
        params = split[1] if len(split) > 1 else ''
        return self.get_proxy_uri(obj) + '?' + params

    def create(self, validated_data):
        # if order is not passed, set it to current max value + 1
        if not validated_data.get('order'):
            layers = self.Meta.model.objects.filter(
                category_id=validated_data.get('category_id'))
            max_order = layers.aggregate(Max('order'))['order__max'] or 0
            validated_data['order'] = max_order + 1
        return super().create(validated_data)
Пример #20
0
class StockSerializer(CompositionMixin, NestedHyperlinkedModelSerializer):
    keyflow = KeyflowInCasestudyField(view_name='keyflowincasestudy-detail',
                                      read_only=True)
    composition = CompositionSerializer()
    publication = IDRelatedField(allow_null=True, required=False)

    parent_lookup_kwargs = {
        'casestudy_pk': 'keyflow__casestudy__id',
        'keyflow_pk': 'keyflow__id',
    }

    class Meta:
        model = Stock
        fields = ('url', 'id', 'origin', 'amount', 'keyflow', 'year',
                  'composition', 'publication', 'waste')
Пример #21
0
class ActivityGroupSerializer(CreateWithUserInCasestudyMixin,
                              NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {
        'casestudy_pk': 'keyflow__casestudy__id',
        'keyflow_pk': 'keyflow__id',
    }
    inputs = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    outputs = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    stocks = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    keyflow = IDRelatedField(read_only=True, required=False)
    nace = serializers.ListField(read_only=True, source='nace_codes')
    flow_count = serializers.IntegerField(read_only=True)

    class Meta:
        model = ActivityGroup
        fields = ('url', 'id', 'code', 'name', 'inputs', 'outputs', 'stocks',
                  'keyflow', 'nace', 'flow_count')
Пример #22
0
class ActivitySerializer(CreateWithUserInCasestudyMixin,
                         NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {
        'casestudy_pk': 'activitygroup__keyflow__casestudy__id',
        'keyflow_pk': 'activitygroup__keyflow__id'
    }
    activitygroup = IDRelatedField()
    activitygroup_url = ActivityGroupField(view_name='activitygroup-detail',
                                           source='activitygroup',
                                           read_only=True)
    activitygroup_name = serializers.CharField(source='activitygroup.name',
                                               read_only=True)
    flow_count = serializers.IntegerField(read_only=True)

    class Meta:
        model = Activity
        fields = ('url', 'id', 'nace', 'name', 'activitygroup',
                  'activitygroup_name', 'activitygroup_url', 'flow_count')
Пример #23
0
class FlowFilterSerializer(serializers.ModelSerializer):
    parent_lookup_kwargs = {
        'casestudy_pk': 'keyflow__casestudy__id',
        'keyflow_pk': 'keyflow__id',
    }
    flow_type = EnumField(enum=FlowType, required=False)
    filter_level = EnumField(enum=NodeLevel, required=False)
    direction = EnumField(enum=Direction, required=False)
    hazardous = EnumField(enum=TriState, required=False)
    avoidable = EnumField(enum=TriState, required=False)
    material = IDRelatedField(allow_null=True, required=False)

    class Meta:
        model = FlowFilter
        fields = ('id', 'name', 'description', 'direction', 'material',
                  'aggregate_materials', 'area_level', 'areas', 'flow_type',
                  'filter_level', 'node_ids', 'process_ids', 'hazardous',
                  'avoidable', 'anonymize', 'included')
        extra_kwargs = {'included': {'required': False}}
Пример #24
0
class KeyflowInCasestudyPostSerializer(InCasestudySerializerMixin,
                                       NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {'casestudy_pk': 'casestudy__id'}
    note = serializers.CharField(required=False, allow_blank=True)
    keyflow = IDRelatedField()

    class Meta:
        model = KeyflowInCasestudy
        fields = ('keyflow', 'note', 'sustainability_statusquo',
                  'sustainability_conclusions')
        extra_kwargs = {
            'sustainability_statusquo': {
                'required': False,
                'allow_null': True
            },
            'sustainability_conclusions': {
                'required': False,
                'allow_null': True
            },
        }
Пример #25
0
class ImplementationQuestionSerializer(SolutionDetailCreateMixin,
                                       NestedHyperlinkedModelSerializer):
    solution = IDRelatedField(read_only=True)
    parent_lookup_kwargs = {
        'casestudy_pk': 'solution__solution_category__keyflow__casestudy__id',
        'keyflow_pk': 'solution__solution_category__keyflow__id',
        'solution_pk': 'solution__id'
    }

    class Meta:
        model = ImplementationQuestion
        fields = ('url', 'id', 'solution', 'question', 'select_values', 'step',
                  'min_value', 'max_value', 'is_absolute')
        extra_kwargs = {
            'step': {
                'required': False
            },
            'select_values': {
                'required': False
            }
        }
Пример #26
0
class SolutionInStrategySerializer(serializers.ModelSerializer):
    parent_lookup_kwargs = {
        'casestudy_pk': 'strategy__keyflow__casestudy__id',
        'keyflow_pk': 'strategy__keyflow__id',
        'strategy_pk': 'strategy__id'
    }
    participants = IDRelatedField(many=True, required=False)
    quantities = ImplementationQuantitySerializer(
        many=True, source='implementation_quantity', required=False)
    areas = ImplementationAreaSerializer(many=True,
                                         source='implementation_area',
                                         required=False)

    class Meta:
        model = SolutionInStrategy
        fields = ('id', 'solution', 'note', 'participants', 'priority',
                  'quantities', 'areas')

    def update(self, instance, validated_data):
        quantities = validated_data.pop('implementation_quantity', [])
        areas = validated_data.pop('implementation_area', [])
        instance = super().update(instance, validated_data)
        for q in quantities:
            # quantities are created automatically, no need to delete them
            quantity = ImplementationQuantity.objects.get(
                question=q['question'], implementation=instance)
            quantity.value = q['value']
            quantity.save()
        for a in areas:
            # quantities are created automatically, no need to delete them
            area = ImplementationArea.objects.get_or_create(
                possible_implementation_area=a['possible_implementation_area'],
                implementation=instance)[0]
            area.geom = a['geom']
            area.save()
        return instance
Пример #27
0
class FractionFlowSerializer(CompositionMixin,
                             NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {
        'casestudy_pk': 'keyflow__casestudy__id',
        'keyflow_pk': 'keyflow__id',
    }
    keyflow = IDRelatedField()
    publication = IDRelatedField(allow_null=True, required=False)
    process = IDRelatedField(allow_null=True, required=False)
    origin = IDRelatedField()
    destination = IDRelatedField()
    material = IDRelatedField()

    #amount = serializers.DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None, localize=False, rounding=None)

    class Meta(FlowSerializer.Meta):
        model = FractionFlow
        fields = ('id', 'origin', 'destination', 'keyflow', 'material',
                  'amount', 'process', 'nace', 'waste', 'avoidable',
                  'hazardous', 'description', 'year', 'publication')
Пример #28
0
class FlowReferenceSerializer(serializers.ModelSerializer):

    origin_activity = IDRelatedField(required=False, allow_null=True)
    destination_activity = IDRelatedField(required=False, allow_null=True)
    material = IDRelatedField(required=False, allow_null=True)
    process = IDRelatedField(required=False, allow_null=True)
    origin_area = IDRelatedField(required=False, allow_null=True)
    destination_area = IDRelatedField(required=False, allow_null=True)

    class Meta:
        model = FlowReference
        fields = ('origin_activity', 'destination_activity', 'material',
                  'include_child_materials', 'process', 'origin_area',
                  'destination_area', 'waste', 'hazardous')
        extra_kwargs = {
            'waste': {
                'required': False
            },
            'hazardous': {
                'required': False
            }
        }
Пример #29
0
class CompositionSerializer(NestedHyperlinkedModelSerializer):
    fractions = ProductFractionSerializer(many=True)
    id = serializers.IntegerField(label='ID',
                                  read_only=False,
                                  required=False,
                                  allow_null=True)
    keyflow = IDRelatedField(read_only=True)
    parent_lookup_kwargs = {}

    class Meta:
        model = Composition
        fields = ('id', 'name', 'nace', 'fractions', 'keyflow')

    def create(self, validated_data):
        fractions = validated_data.pop('fractions')
        instance = super().create(validated_data)
        validated_data['fractions'] = fractions
        self.update(instance, validated_data)
        return instance

    def update(self, instance, validated_data):
        """update the user-attributes, including fraction information"""
        composition = instance

        # handle product fractions
        new_fractions = validated_data.pop('fractions', None)

        if new_fractions is not None:
            product_fractions = ProductFraction.objects.filter(
                composition=composition)
            # delete existing rows not needed any more
            ids = [
                fraction.get('id') for fraction in new_fractions
                if fraction.get('id') is not None
            ]
            to_delete = product_fractions.exclude(id__in=ids)
            to_delete.delete()
            # add or update new fractions
            for new_fraction in new_fractions:
                material_id = getattr(new_fraction.get('material'), 'id')
                material = Material.objects.get(id=material_id)
                fraction_id = new_fraction.get('id')
                # create new fraction
                if (fraction_id is None
                        or len(product_fractions.filter(id=fraction_id)) == 0):
                    fraction = ProductFraction(composition=composition)
                # change existing fraction
                else:
                    fraction = product_fractions.get(id=fraction_id)

                for attr, value in new_fraction.items():
                    if attr in ('composition', 'id'):
                        continue
                    setattr(fraction, attr, value)
                fraction.save()

        # update other attributes
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance
Пример #30
0
class StrategySerializer(CreateWithUserInCasestudyMixin,
                         NestedHyperlinkedModelSerializer):
    parent_lookup_kwargs = {
        'casestudy_pk': 'keyflow__casestudy__id',
        'keyflow_pk': 'keyflow__id',
    }
    coordinating_stakeholder = IDRelatedField()
    user = IDRelatedField(read_only=True)
    status_text = serializers.SerializerMethodField()
    solutions = serializers.SerializerMethodField()
    affected_activities = serializers.SerializerMethodField()

    class Meta:
        model = Strategy
        fields = ('url', 'id', 'name', 'user', 'coordinating_stakeholder',
                  'solutions', 'status', 'status_text', 'affected_activities')

        extra_kwargs = {'status': {'read_only': True}}

    def get_solutions(self, obj):
        sii = obj.solutioninstrategy.all()
        return sii.values_list('solution__id', flat=True)

    def get_status_text(self, obj):
        if obj.status == 0:
            return _('not calculated yet')
        if obj.status == 1:
            delta = timezone.now() - obj.date
            return '{} @{} {} - {}s {}'.format(
                _('calculation started'),
                obj.date.strftime("%d.%m.%Y, %H:%M:%S"), _('(server time)'),
                round(delta.total_seconds()), _('elapsed'))
        if obj.status == 2:
            return '{} @{} {}'.format(_('calculation finished'),
                                      obj.date.strftime("%d.%m.%Y, %H:%M:%S"),
                                      _('(server time)'))
        return ''

    def update(self, instance, validated_data):
        """
        update the strategy-attributes,
        including selected solutions
        """
        strategy = instance

        # handle solutions
        new_solutions = validated_data.pop('solutions', None)
        if new_solutions is not None:
            SolutionInStrategyModel = Strategy.solutions.through
            solution_qs = SolutionInStrategyModel.objects.filter(
                strategy=strategy)
            # delete existing solutions
            solution_qs.exclude(
                solution_id__in=(sol.id for sol in new_solutions)).delete()
            # add or update new solutions
            for sol in new_solutions:
                SolutionInStrategyModel.objects.update_or_create(
                    strategy=strategy, solution=sol)

        # update other attributes
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance

    def get_affected_activities(self, obj):
        new_flows = FractionFlow.objects.filter(strategy=obj, amount__gt=0)
        modified = StrategyFractionFlow.objects.filter(strategy=obj)
        modified_flows = FractionFlow.objects.filter(
            id__in=modified.values_list('fractionflow__id'))
        activities = list(
            new_flows.values_list(
                'origin__activity__id',
                'destination__activity__id',
            ))
        activities += list(
            modified_flows.values_list(
                'origin__activity__id',
                'destination__activity__id',
            ))
        activities = set([i for s in activities for i in s])
        return activities