* Vietnamese translation incomplete

Tour operator serializer

Tour operator serializer (English fallback)

Aug. 17, 2025

Posted by admin

Nhom

Notes

 

Tour Operators Serializers - Detailed Analysis

File Overview

Purpose: API data serialization for tour operators system Locationserializers.py Framework: Django REST Framework (DRF) serializers Function: Convert Django model instances to/from JSON for API endpoints

Import Dependencies

from rest_framework import serializers

from .models import Tour, TourOperator, TourBooking, TourCategory, TourSchedule, TourGuide

Key Components:

  • rest_framework.serializers: DRF serialization framework
  • Model imports: All core tour operator models for API exposure

 

 

Serializer Classes Detailed Breakdown

 

 

1. TourCategorySerializer

class TourCategorySerializer(serializers.ModelSerializer):

    class Meta:

        model = TourCategory

        fields = ['id', 'name', 'name_vi', 'icon']

Purpose: Serialize tour categories for API consumption Fields Exposed:

  • id: Primary key identifier
  • name: Category name in English
  • name_vi: Vietnamese translation
  • icon: Visual icon identifier

API Usage:

  • Category listings for tour filtering
  • Dropdown options in booking forms
  • Category-based tour browsing

Sample JSON Output:

{

    "id": 1,

    "name": "Adventure Tours",

    "name_vi": "Tour Phiêu Lưu",

    "icon": "fa-mountain"

}

 

 

2. TourOperatorSerializer

class TourOperatorSerializer(serializers.ModelSerializer):

    class Meta:

        model = TourOperator

        fields = [

            'id', 'name', 'name_vi', 'description', 'description_vi',

            'operator_type', 'city', 'country', 'average_rating',

            'total_reviews', 'total_tours', 'is_verified'

        ]

Purpose: Serialize tour operator information for API Fields Breakdown:

Basic Information:

  • id: Unique operator identifier
  • name / name_vi: Multilingual operator names
  • description / description_vi: Multilingual descriptions

Classification:

  • operator_type: Business type (local, international, specialty)
  • city / country: Geographic location

Business Metrics:

  • average_rating: Customer rating average
  • total_reviews: Number of customer reviews
  • total_tours: Active tour count (maintained by signals)
  • is_verified: Verification status badge

API Use Cases:

  • Operator directory listings
  • Operator comparison features
  • Trust indicators for customers
  • Search and filtering operations

Sample JSON Output:

{

    "id": 5,

    "name": "Saigon Adventure Tours",

    "name_vi": "Tour Phiêu Lưu Sài Gòn",

    "description": "Professional tour operator specializing in Vietnam adventures",

    "description_vi": "Nhà tổ chức tour chuyên nghiệp chuyên về phiêu lưu Việt Nam",

    "operator_type": "local",

    "city": "Ho Chi Minh City",

    "country": "Vietnam",

    "average_rating": 4.8,

    "total_reviews": 156,

    "total_tours": 23,

    "is_verified": true

}

 

 

3. TourScheduleSerializer

class TourScheduleSerializer(serializers.ModelSerializer):

    remaining_spots = serializers.ReadOnlyField()

    

    class Meta:

        model = TourSchedule

        fields = [

            'id', 'start_date', 'start_time', 'available_spots',

            'booked_spots', 'remaining_spots', 'price_override'

        ]

Purpose: Serialize tour scheduling and availability data Special Features:

  • remaining_spots: Calculated field (read-only)
  • Real-time availability tracking

Fields Explanation:

  • id: Schedule instance identifier
  • start_date / start_time: Tour departure timing
  • available_spots: Maximum capacity
  • booked_spots: Current bookings count
  • remaining_spots: Available capacity (calculated)
  • price_override: Special pricing for this schedule

Business Logic:

  • Enables real-time availability checking
  • Supports dynamic pricing
  • Prevents overbooking through API

Sample JSON Output:

{

    "id": 45,

    "start_date": "2025-08-15",

    "start_time": "08:00:00",

    "available_spots": 20,

    "booked_spots": 12,

    "remaining_spots": 8,

    "price_override": 150.00

}

 

 

4. TourGuideSerializer

class TourGuideSerializer(serializers.ModelSerializer):

    name = serializers.CharField(source='user.get_full_name', read_only=True)

    

    class Meta:

        model = TourGuide

        fields = [

            'id', 'name', 'bio', 'bio_vi', 'years_experience',

            'average_rating', 'total_tours_guided', 'languages'

        ]

Purpose: Serialize tour guide profiles for API Special Features:

  • name: Derived from related User model via source='user.get_full_name'
  • Read-only calculated fields

Fields BreakdownPersonal Information:

  • id: Guide identifier
  • name: Full name from User profile
  • bio / bio_vi: Multilingual biographical information

Professional Data:

  • years_experience: Industry experience
  • average_rating: Customer ratings
  • total_tours_guided: Tour count (signals-maintained)
  • languages: Spoken languages list

API Applications:

  • Guide selection for custom tours
  • Guide profile displays
  • Multilingual tour assignments

 

 

5. TourSerializer (Main Serializer)

class TourSerializer(serializers.ModelSerializer):

    tour_operator = TourOperatorSerializer(read_only=True)

    categories = TourCategorySerializer(many=True, read_only=True)

    schedules = TourScheduleSerializer(many=True, read_only=True)

    duration_display = serializers.ReadOnlyField()

    

    class Meta:

        model = Tour

        fields = [

            'id', 'uuid', 'title', 'title_vi', 'slug', 'short_description',

            'short_description_vi', 'description', 'description_vi',

            'tour_operator', 'categories', 'tour_type', 'difficulty',

            'duration_days', 'duration_hours', 'duration_display',

            'start_location', 'end_location', 'min_participants',

            'max_participants', 'base_price', 'price_currency',

            'includes_accommodation', 'includes_meals', 'includes_transport',

            'includes_guide', 'includes_tickets', 'main_image', 'video_url',

            'average_rating', 'total_reviews', 'total_bookings',

            'is_featured', 'schedules'

        ]

Purpose: Complete tour information serialization Nested Relationships:

  • tour_operator: Full operator details
  • categories: Multiple category associations
  • schedules: All available tour dates/times

Field Categories:

Identification:

  • id, uuid, slug: Various identifiers
  • title / title_vi: Multilingual tour names

Descriptions:

  • short_description / short_description_vi: Brief summaries
  • description / description_vi: Detailed information

Tour Details:

  • tour_type, difficulty: Classification
  • duration_days, duration_hours, duration_display: Timing
  • start_location, end_location: Geography
  • min_participants, max_participants: Capacity limits

Pricing & Inclusions:

  • base_price, price_currency: Cost information
  • includes_*: Boolean flags for inclusions (accommodation, meals, etc.)

Media & Marketing:

  • main_image, video_url: Visual content
  • is_featured: Promotional flag

Statistics:

  • average_rating, total_reviews, total_bookings: Performance metrics

 

 

6. TourBookingSerializer (Complex Serializer)

class TourBookingSerializer(serializers.ModelSerializer):

    tour = TourSerializer(read_only=True)

    tour_id = serializers.IntegerField(write_only=True)

    schedule_id = serializers.IntegerField(write_only=True)

    

    class Meta:

        model = TourBooking

        fields = [

            'id', 'booking_number', 'tour', 'tour_id', 'schedule_id',

            'lead_traveler_name', 'lead_traveler_email', 'lead_traveler_phone',

            'adult_count', 'child_count', 'senior_count', 'total_participants',

            'total_price', 'special_requests', 'dietary_requirements',

            'accessibility_needs', 'booking_status', 'payment_status',

            'booking_date'

        ]

        read_only_fields = ['booking_number', 'total_price', 'booking_date']

Purpose: Handle tour booking creation and management Advanced Features:

Read/Write Field Separation:

  • tour: Full tour details (read-only for output)
  • tour_id: Simple ID for input (write-only)
  • schedule_id: Schedule selection (write-only)

Protected Fields:

  • booking_number: Auto-generated
  • total_price: Calculated from participants + tour price
  • booking_date: Timestamp managed automatically

Customer Information:

  • Lead traveler contact details
  • Participant counts by age group
  • Special requirements tracking

 

 

Custom Create Method

def create(self, validated_data):

    tour_id = validated_data.pop('tour_id')

    schedule_id = validated_data.pop('schedule_id')

    

    tour = Tour.objects.get(id=tour_id)

    schedule = TourSchedule.objects.get(id=schedule_id, tour=tour)

    

    booking = TourBooking.objects.create(

        tour=tour,

        schedule=schedule,

        customer=self.context['request'].user,

        **validated_data

    )

    

    return booking

Purpose: Custom booking creation logic Process Flow:

  1. Data Extraction: Remove IDs from validated data
  2. Object Resolution: Convert IDs to model instances
  3. Validation: Ensure schedule belongs to selected tour
  4. User Injection: Add authenticated user as customer
  5. Instance Creation: Create booking with all data

Business Logic:

  • Prevents schedule/tour mismatches
  • Automatically assigns current user as customer
  • Maintains data integrity through validation

API Integration Architecture

Serializer Hierarchy

TourSerializer (Main)

── TourOperatorSerializer (Nested)

── TourCategorySerializer (Many-to-Many)

└── TourScheduleSerializer (Many-to-Many)

TourBookingSerializer

── TourSerializer (Nested, Read-only)

└── Custom create() method

 

 

Use Cases by Serializer

TourCategorySerializer:

  • /api/categories/ - Category listings
  • Tour filtering endpoints
  • Mobile app category selectors

TourOperatorSerializer:

  • /api/operators/ - Operator directory
  • Operator search and filtering
  • Trust badge displays

TourScheduleSerializer:

  • Real-time availability checking
  • Calendar displays
  • Booking date selection

TourGuideSerializer:

  • Guide profile APIs
  • Custom tour guide selection
  • Multilingual guide matching

TourSerializer:

  • /api/tours/ - Main tour listings
  • Tour detail pages
  • Search and filter results

TourBookingSerializer:

  • /api/bookings/ - Booking management
  • Booking creation endpoints
  • Customer booking history

Performance Considerations

Nested Serialization:

  • Reduces API calls by including related data
  • May increase response size for complex tours
  • Consider using select_related() and prefetch_related() in views

Read-Only Fields:

  • Calculated fields prevent unnecessary database writes
  • Improves data consistency
  • Reduces API complexity

Write-Only Fields:

  • Simplifies API input requirements
  • Maintains security by hiding internal relationships
  • Enables custom validation logic

This serializer system provides a robust, efficient API layer for the tour operators platform, supporting complex business logic while maintaining clean, RESTful interfaces for frontend consumption.

 

Vietnamese translation is not available for this article. Showing English content:

Nhom

Notes

 

Tour Operators Serializers - Detailed Analysis

File Overview

Purpose: API data serialization for tour operators system Locationserializers.py Framework: Django REST Framework (DRF) serializers Function: Convert Django model instances to/from JSON for API endpoints

Import Dependencies

from rest_framework import serializers

from .models import Tour, TourOperator, TourBooking, TourCategory, TourSchedule, TourGuide

Key Components:

  • rest_framework.serializers: DRF serialization framework
  • Model imports: All core tour operator models for API exposure

 

 

Serializer Classes Detailed Breakdown

 

 

1. TourCategorySerializer

class TourCategorySerializer(serializers.ModelSerializer):

    class Meta:

        model = TourCategory

        fields = ['id', 'name', 'name_vi', 'icon']

Purpose: Serialize tour categories for API consumption Fields Exposed:

  • id: Primary key identifier
  • name: Category name in English
  • name_vi: Vietnamese translation
  • icon: Visual icon identifier

API Usage:

  • Category listings for tour filtering
  • Dropdown options in booking forms
  • Category-based tour browsing

Sample JSON Output:

{

    "id": 1,

    "name": "Adventure Tours",

    "name_vi": "Tour Phiêu Lưu",

    "icon": "fa-mountain"

}

 

 

2. TourOperatorSerializer

class TourOperatorSerializer(serializers.ModelSerializer):

    class Meta:

        model = TourOperator

        fields = [

            'id', 'name', 'name_vi', 'description', 'description_vi',

            'operator_type', 'city', 'country', 'average_rating',

            'total_reviews', 'total_tours', 'is_verified'

        ]

Purpose: Serialize tour operator information for API Fields Breakdown:

Basic Information:

  • id: Unique operator identifier
  • name / name_vi: Multilingual operator names
  • description / description_vi: Multilingual descriptions

Classification:

  • operator_type: Business type (local, international, specialty)
  • city / country: Geographic location

Business Metrics:

  • average_rating: Customer rating average
  • total_reviews: Number of customer reviews
  • total_tours: Active tour count (maintained by signals)
  • is_verified: Verification status badge

API Use Cases:

  • Operator directory listings
  • Operator comparison features
  • Trust indicators for customers
  • Search and filtering operations

Sample JSON Output:

{

    "id": 5,

    "name": "Saigon Adventure Tours",

    "name_vi": "Tour Phiêu Lưu Sài Gòn",

    "description": "Professional tour operator specializing in Vietnam adventures",

    "description_vi": "Nhà tổ chức tour chuyên nghiệp chuyên về phiêu lưu Việt Nam",

    "operator_type": "local",

    "city": "Ho Chi Minh City",

    "country": "Vietnam",

    "average_rating": 4.8,

    "total_reviews": 156,

    "total_tours": 23,

    "is_verified": true

}

 

 

3. TourScheduleSerializer

class TourScheduleSerializer(serializers.ModelSerializer):

    remaining_spots = serializers.ReadOnlyField()

    

    class Meta:

        model = TourSchedule

        fields = [

            'id', 'start_date', 'start_time', 'available_spots',

            'booked_spots', 'remaining_spots', 'price_override'

        ]

Purpose: Serialize tour scheduling and availability data Special Features:

  • remaining_spots: Calculated field (read-only)
  • Real-time availability tracking

Fields Explanation:

  • id: Schedule instance identifier
  • start_date / start_time: Tour departure timing
  • available_spots: Maximum capacity
  • booked_spots: Current bookings count
  • remaining_spots: Available capacity (calculated)
  • price_override: Special pricing for this schedule

Business Logic:

  • Enables real-time availability checking
  • Supports dynamic pricing
  • Prevents overbooking through API

Sample JSON Output:

{

    "id": 45,

    "start_date": "2025-08-15",

    "start_time": "08:00:00",

    "available_spots": 20,

    "booked_spots": 12,

    "remaining_spots": 8,

    "price_override": 150.00

}

 

 

4. TourGuideSerializer

class TourGuideSerializer(serializers.ModelSerializer):

    name = serializers.CharField(source='user.get_full_name', read_only=True)

    

    class Meta:

        model = TourGuide

        fields = [

            'id', 'name', 'bio', 'bio_vi', 'years_experience',

            'average_rating', 'total_tours_guided', 'languages'

        ]

Purpose: Serialize tour guide profiles for API Special Features:

  • name: Derived from related User model via source='user.get_full_name'
  • Read-only calculated fields

Fields BreakdownPersonal Information:

  • id: Guide identifier
  • name: Full name from User profile
  • bio / bio_vi: Multilingual biographical information

Professional Data:

  • years_experience: Industry experience
  • average_rating: Customer ratings
  • total_tours_guided: Tour count (signals-maintained)
  • languages: Spoken languages list

API Applications:

  • Guide selection for custom tours
  • Guide profile displays
  • Multilingual tour assignments

 

 

5. TourSerializer (Main Serializer)

class TourSerializer(serializers.ModelSerializer):

    tour_operator = TourOperatorSerializer(read_only=True)

    categories = TourCategorySerializer(many=True, read_only=True)

    schedules = TourScheduleSerializer(many=True, read_only=True)

    duration_display = serializers.ReadOnlyField()

    

    class Meta:

        model = Tour

        fields = [

            'id', 'uuid', 'title', 'title_vi', 'slug', 'short_description',

            'short_description_vi', 'description', 'description_vi',

            'tour_operator', 'categories', 'tour_type', 'difficulty',

            'duration_days', 'duration_hours', 'duration_display',

            'start_location', 'end_location', 'min_participants',

            'max_participants', 'base_price', 'price_currency',

            'includes_accommodation', 'includes_meals', 'includes_transport',

            'includes_guide', 'includes_tickets', 'main_image', 'video_url',

            'average_rating', 'total_reviews', 'total_bookings',

            'is_featured', 'schedules'

        ]

Purpose: Complete tour information serialization Nested Relationships:

  • tour_operator: Full operator details
  • categories: Multiple category associations
  • schedules: All available tour dates/times

Field Categories:

Identification:

  • id, uuid, slug: Various identifiers
  • title / title_vi: Multilingual tour names

Descriptions:

  • short_description / short_description_vi: Brief summaries
  • description / description_vi: Detailed information

Tour Details:

  • tour_type, difficulty: Classification
  • duration_days, duration_hours, duration_display: Timing
  • start_location, end_location: Geography
  • min_participants, max_participants: Capacity limits

Pricing & Inclusions:

  • base_price, price_currency: Cost information
  • includes_*: Boolean flags for inclusions (accommodation, meals, etc.)

Media & Marketing:

  • main_image, video_url: Visual content
  • is_featured: Promotional flag

Statistics:

  • average_rating, total_reviews, total_bookings: Performance metrics

 

 

6. TourBookingSerializer (Complex Serializer)

class TourBookingSerializer(serializers.ModelSerializer):

    tour = TourSerializer(read_only=True)

    tour_id = serializers.IntegerField(write_only=True)

    schedule_id = serializers.IntegerField(write_only=True)

    

    class Meta:

        model = TourBooking

        fields = [

            'id', 'booking_number', 'tour', 'tour_id', 'schedule_id',

            'lead_traveler_name', 'lead_traveler_email', 'lead_traveler_phone',

            'adult_count', 'child_count', 'senior_count', 'total_participants',

            'total_price', 'special_requests', 'dietary_requirements',

            'accessibility_needs', 'booking_status', 'payment_status',

            'booking_date'

        ]

        read_only_fields = ['booking_number', 'total_price', 'booking_date']

Purpose: Handle tour booking creation and management Advanced Features:

Read/Write Field Separation:

  • tour: Full tour details (read-only for output)
  • tour_id: Simple ID for input (write-only)
  • schedule_id: Schedule selection (write-only)

Protected Fields:

  • booking_number: Auto-generated
  • total_price: Calculated from participants + tour price
  • booking_date: Timestamp managed automatically

Customer Information:

  • Lead traveler contact details
  • Participant counts by age group
  • Special requirements tracking

 

 

Custom Create Method

def create(self, validated_data):

    tour_id = validated_data.pop('tour_id')

    schedule_id = validated_data.pop('schedule_id')

    

    tour = Tour.objects.get(id=tour_id)

    schedule = TourSchedule.objects.get(id=schedule_id, tour=tour)

    

    booking = TourBooking.objects.create(

        tour=tour,

        schedule=schedule,

        customer=self.context['request'].user,

        **validated_data

    )

    

    return booking

Purpose: Custom booking creation logic Process Flow:

  1. Data Extraction: Remove IDs from validated data
  2. Object Resolution: Convert IDs to model instances
  3. Validation: Ensure schedule belongs to selected tour
  4. User Injection: Add authenticated user as customer
  5. Instance Creation: Create booking with all data

Business Logic:

  • Prevents schedule/tour mismatches
  • Automatically assigns current user as customer
  • Maintains data integrity through validation

API Integration Architecture

Serializer Hierarchy

TourSerializer (Main)

── TourOperatorSerializer (Nested)

── TourCategorySerializer (Many-to-Many)

└── TourScheduleSerializer (Many-to-Many)

TourBookingSerializer

── TourSerializer (Nested, Read-only)

└── Custom create() method

 

 

Use Cases by Serializer

TourCategorySerializer:

  • /api/categories/ - Category listings
  • Tour filtering endpoints
  • Mobile app category selectors

TourOperatorSerializer:

  • /api/operators/ - Operator directory
  • Operator search and filtering
  • Trust badge displays

TourScheduleSerializer:

  • Real-time availability checking
  • Calendar displays
  • Booking date selection

TourGuideSerializer:

  • Guide profile APIs
  • Custom tour guide selection
  • Multilingual guide matching

TourSerializer:

  • /api/tours/ - Main tour listings
  • Tour detail pages
  • Search and filter results

TourBookingSerializer:

  • /api/bookings/ - Booking management
  • Booking creation endpoints
  • Customer booking history

Performance Considerations

Nested Serialization:

  • Reduces API calls by including related data
  • May increase response size for complex tours
  • Consider using select_related() and prefetch_related() in views

Read-Only Fields:

  • Calculated fields prevent unnecessary database writes
  • Improves data consistency
  • Reduces API complexity

Write-Only Fields:

  • Simplifies API input requirements
  • Maintains security by hiding internal relationships
  • Enables custom validation logic

This serializer system provides a robust, efficient API layer for the tour operators platform, supporting complex business logic while maintaining clean, RESTful interfaces for frontend consumption.

 

Attached Files

0 files found.

You are viewing this article in public mode. Some features may be limited.