Home > Enterprise >  How to get a list of existing student names in Django?
How to get a list of existing student names in Django?

Time:11-20

I am new to Django rest framework, I want to get a list of the student first names(only) when it is existed. can anyone help me?

In my models.py

class School(models.Model):
    name = models.CharField(max_length=100, null=False, blank=False)
    city = models.CharField(max_length=100, null=False, blank=False)
    street = models.CharField(max_length=100, null=False, blank=False)

    def __str__(self):
        return f"{self.city}->{self.street}->{self.name}"

class Student(models.Model):
    school_id = models.ForeignKey(School, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=100, null=False, blank=False)
    last_name = models.CharField(max_length=100, null=False, blank=False)

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

In my serializers.py:

class StudentSerializer(serializers.Serializer):
    class Meta:
        model = Student
        fields = ['first_name']
   

class SchoolSerializer(serializers.Serializer):
    is_existing_student = = serializers.BooleanField()
    student = StudentSerializer(many=True, read_only=True)

    class Meta:
        model = School
        fields = ['is_existing_student','student']

In my views.py:

class schoolViewSet(viewsets.ModelViewSet):
    serializer_class = SchoolSerializer
    queryset = School.objects.all()

In this picture you can see how it should look like [1]: https://i.stack.imgur.com/bR8cN.png

CodePudding user response:

you can try using values() method or values-list() method so you can do something like

Student.objects.values_list('first_name') 

or

Student.objects.values('first_name')

https://docs.djangoproject.com/en/3.2/ref/models/querysets/#values-list

CodePudding user response:

try adding a student view in your views.py then use values() method

class StudentViewSet(viewsets.ModelViewSet):
    serializer_class = StudentSerializer
    queryset = Student.objects.values('first_name')

CodePudding user response:

From what you define on first_name model field, i.e null=False, blank=False. It means the field cannot be empty.

first_name = models.CharField(max_length=100, null=False, blank=False)

Which means all your models call will always have first_name required

Meanwhile, if you still want to be sure that your query returns items with first_name, do this

queryset = School.objects.exclude(student__first_name=None) 
  • Related