0
escs = esc.objects.filter(Education_Levels__in=studentenroll.values_list('Education_Levels')).order_by(
        'id')
edulevel = StudentsEnrollmentRecord.objects.filter(ESC__in=escs.values_list('id')).order_by(
        'pk').first()

When I tried this print("ESC", edulevel) I received this message.

ESC None

how do I get the id of esc?

This is my model:

class StudentsEnrollmentRecord(models.Model):
    Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True)
    Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True)
    ESC = models.ForeignKey(esc, on_delete=models.CASCADE,null=True,blank=True)
Tanjim Ahmed Khan
  • 650
  • 1
  • 9
  • 21

1 Answers1

0

Two possibilities:

1: you have set null=True in foreign key which means that the query set returns object which has null in ecs foreign key so you can either remove that null constraint or check if null before any operation of the result of query_set

2nd: It is because your query set is not returning any object (There is no model object in your db which satisfies the filter conditions)

You can confirm this by:

try:
 edulevel = StudentsEnrollmentRecord.objects.filter(ESC__in=escs.values_list('id')).order_by(
        'pk').first()
except StudentsEnrollmentRecord.DoesNotExist:
  print("I Did not find anything. Try adding objects first")

You can see all objects of ecs model

#This is only for debugging process to see what objects do you actually have to opt for suitable filters
query_set = esc.objects.all()
print("ecs")
print(query_set)
query_set = StudentsEnrollmentRecord.objects.all()
print("SER")
print(query_set)

UPDATE:

You can also use if condition like this

edulevel = StudentsEnrollmentRecord.objects.filter(ESC__in=escs.values_list('id')).order_by(
        'pk').first()

if(edulevel)
  print(edulevel)

You can also use count like this

edulevel = StudentsEnrollmentRecord.objects.filter(ESC__in=escs.values_list('id')).order_by(
        'pk').first()

if(edulevel.count()>0)
  print(edulevel)

Last but not least you can also use exists() as explained here https://stackoverflow.com/a/9089028/11979793

Hashir
  • 390
  • 5
  • 20
  • is there any way to solve that my problem not using try catch? –  May 21 '20 at 09:31
  • What i mean sir is, if that selected data have ID greater than or equal to lets say 5, for example, the ID of the apple is 10, apple >=5 –  May 21 '20 at 10:10
  • kindly check the updated answer, i believe you re facing problem#1 – Hashir May 21 '20 at 10:10
  • sir kindly check this question https://stackoverflow.com/questions/61931877/typeerror-not-supported-between-instances-of-queryset-and-int –  May 21 '20 at 10:12