Home > OS >  get the id of a related field and save data
get the id of a related field and save data

Time:01-07

I'm kinda new to DRF, I am building a database for attendance. I want to save an instance of AttendanceSlot in my Attendance but I don't know how to get id, so i can save it... models.py

class AttendanceSlot(models.Model):
    department_id = models.ForeignKey("students.Department", verbose_name=_("department id"), on_delete=models.CASCADE)
    course_id = models.ForeignKey("students.Course", verbose_name=_("course id"), related_name= 'course', on_delete=models.CASCADE)
    lecturer_id = models.ForeignKey("lecturers.Lecturer", on_delete=models.CASCADE)
    date = models.DateField(_("attendance date"), auto_now=False, auto_now_add=True)
    start_time = models.TimeField(_("start time"), auto_now=False, auto_now_add=False)
    end_time = models.TimeField(auto_now=False, auto_now_add=False)
    longitude = models.CharField(_("longitude"), max_length=50)
    latitude = models.CharField(_("latitude"), max_length=50)
    radius = models.CharField(_("radius"), max_length=50)

    def __str__(self):
        return '{0}'.format(self.course_id.course_code)

class Attendance(models.Model):
    slot_id = models.ForeignKey("attendance.AttendanceSlot", verbose_name=_("attendance slot"), on_delete=models.CASCADE)
    student_id = models.ForeignKey("students.Student", on_delete=models.CASCADE)
    performance = models.CharField(max_length=50)

serializers.py

class AttendanceSerializer(serializers.ModelSerializer):
    # student_id = serializers.SlugField(read_only=True)
    slot_id = serializers.PrimaryKeyRelatedField(queryset=AttendanceSlot.objects.all(), many=False)
    class Meta:
        model = Attendance
        fields = ['student_id', 'slot_id', 'performance']

views.py

class Attendance(ListCreateAPIView):
    queryset = Attendance.objects.all()
    serializer_class = AttendanceSerializer

    def get_queryset(self, *args, **kwargs):
        
        id = self.kwargs['pk']
        slot = AttendanceSlot.objects.get(id=id)
        return slot

    def perform_create(self, serializer):
        serializer.save(user = self.request.user, slot_id=self.get_queryset())
        return super().perform_create(serializer)

urls.py

path('<int:pk>/', views.Attendance.as_view(), name='attendance'),

CodePudding user response:

Seems like you are not receiving the slot_id from the request but getting it from the database. So you don't even need to specify the slot_id in your serializer. So change your views.py and serializers.py files like these

# views.py
class Attendance(ListCreateAPIView):
    queryset = Attendance.objects.all()
    serializer_class = AttendanceSerializer

and

# serializers.py
class AttendanceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Attendance
        fields = ['student_id',  'performance']

    def create(self, validated_data):
        slot_id = self.context['view'].kwargs['pk']
        slot = AttendanceSlot.objects.get(id=slot_id)
        return Attendance.objects.create(slot=slot, **validated_data)

Note: The above serializer is expecting that you will pass student_id and performance in the body of your POST request.

  • Related