Cipher
Cipher

Reputation: 2122

Rename Fields of Model in Serializer and Form - Django

I want to change field names. In my model field name start with prefix timesheet. And when i am using api i have to use that timesheet prefix. I want to remove that prefix instead keep jobs, clock_in_date, clock_out_date.... How can i rename field names so that when i am send data from api body should contain names without timesheet prefix

class TimesheetSerializer(serializers.ModelSerializer):

    timesheet_hours = TimesheetHourSerializer(many=True, read_only=True)

    class Meta:
        model = TimesheetEntry
        fields = [
            'id',
            'timesheet_jobs',
            'timesheet_clock_in_date',
            'timesheet_clock_in_time',
            'timesheet_clock_out_date',
            'timesheet_clock_out_time',
            'timesheet_note',
            'timesheet_hours',
        ]

Models.py

class TimesheetEntry(models.Model):
    timesheet_users = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_users')
    timesheet_jobs = models.ForeignKey(Jobs, on_delete=models.CASCADE,related_name='timesheet_jobs', blank=True, null=True)
    timesheet_clock_in_date = models.DateField()
    timesheet_clock_in_time = models.TimeField()
    timesheet_clock_on = models.DateTimeField(auto_now_add=True)
    timesheet_clock_in_by = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_user_clock_in_by')
    timesheet_clock_out_date = models.DateField(blank=True, null=True)
    timesheet_clock_out_time = models.TimeField(blank=True, null=True)

Upvotes: 0

Views: 314

Answers (1)

Exprator
Exprator

Reputation: 27513

class TimesheetSerializer(serializers.ModelSerializer):
    timesheet_hours = TimesheetHourSerializer(many=True, read_only=True)
    jobs = serializers.CharField(source='timesheet_jobs')

    class Meta:
        model = TimesheetEntry
        fields = [
            'id',
            'jobs',
            .......
        ]

you can simply use this. This would work for write operations also

Upvotes: 5

Related Questions