Skip to content

Conversation

@shaohuzhang1
Copy link
Contributor

fix: Exclude unnecessary query fields

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Dec 10, 2025

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Dec 10, 2025

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

'meta': a.get("meta"), 'run_time': a.get("run_time"), 'create_time': a.get("create_time")})

def action(self, instance: Dict, user, with_valid=True):
if with_valid:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code looks generally correct but contains some minor improvements that might enhance its readability and efficiency:

  1. Method Naming Consistency: Ensure consistent naming conventions throughout the code. For example, use filter instead of query_set, is_valid instead of just validate.

  2. Variable Names: Use descriptive variable names such as query_set, _result, etc.

  3. Dictionary Method Syntax: Use dictionary unpacking (**instance) to simplify passing instance variables.

Here's an improved version of the code:

class KnowledgeWorkflowActionSerializer(serializers.Serializer):
    knowledge_id = serializers.UUIDField(required=True, label=_('knowledge id'))

    def _get_queryset(self, instance: dict) -> QuerySet:
        queryset = QuerySet(KnowledgeAction).filter(
            knowledge_id=self.data.get('knowledge_id')
        )
        
        if instance.get("user_name"):
            queryset = queryset.filter(meta__user_name__icontains=instance.get('user_name'))
        
        if instance.get('state'):
            queryset = queryset.filter(state=instance['state'])
        
        if instance.get('created_after') and instance.get('created_before'):
            queryset = queryset.filter(create_time__range=[instance['created_after'], instance['created_before']])
            # Assuming created_after/before exist and are valid datetime strings
        
        return queryset

    def list(self, instance: dict, is_valid: bool = True):
        if is_valid:
            self.is_valid(raise_exception=True)
            serializer = KnowledgeWorkflowActionListQuerySerializer(data=instance)
            serializer.is_valid(raise_exception=True)
        
        return [{'id': obj.id, 'knowledge_id': obj.knowledge_id, 'state': obj.state,
                 'meta': obj.meta, 'run_time': obj.run_time, 'create_time': obj.create_time} for obj in self._get_queryset(instance)]

    @staticmethod
    def page(current_page: int, page_size: int, instance: dict, is_valid: bool = True):
        if is_valid:
            self.is_valid(raise_exception=True)
            serializer = KnowledgeWorkflowActionListQuerySerializer(data=instance)
            serializer.is_valid(raise_exception=True)

        return page_search(current_page, page_size, lambda obj: {
            'id': obj.get("id"),
            'knowledge_id': obj.get("knowledge_id"),
            'state': obj.get("state"),
            'meta': obj.get("meta"),
            'run_time': obj.get("run_time"),
            'create_time': obj.get("create_time")
        }, instance['_get_queryset'], instance.copy())

    @staticmethod
    def create(action_data: dict, user: User) -> dict:
        """
        Create a new knowledge workflow action record using given data.
        
        Args:
            action_data (dict): Input data for action creation.
            user (User): The user creating the action.
            
        Returns:
            dict: A message about the success of the action creation.
        """
        try:
            action = KnowledgeAction.objects.create(user=user, **action_data)
            return {"message": "Knowledge Workflow Action created successfully", "data": {"id": action.pk}}
        except IntegrityError as e:
            return {"error": str(e)}

Key Improvements:

  • Consistent Method Naming: Used _ prepended to certain methods like _get_queryset.
  • Descriptive Variable Names: E.g., _result for storing the result of the query.
  • Static Methods: Moved static methods where applicable, such as page, assuming they don't require access to the instance directly.
  • Type Annotations: Added type annotations to improve understanding and potentially aid with IDE features.
  • Error Handling: Enhanced error handling for the create method to catch and respond more gracefully to database integrity errors.

Additionally, ensure you have appropriate imports and context for User, page_search, and any other dependencies used in this implementation.

@zhanweizhang7 zhanweizhang7 merged commit 8456566 into v2 Dec 10, 2025
3 of 5 checks passed
@zhanweizhang7 zhanweizhang7 deleted the pr@v2@fix_exclude branch December 10, 2025 03:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants