django get function retrun true false
The get() function in Django returns either an instance of a model or None if no instance is found. It does not return a Boolean value of True or False.
However, you can use the exists() method on the queryset returned by get() to check if the instance exists in the database. This method returns a Boolean value of True if the instance exists and False otherwise.
Example:
from myapp.models import MyModel
# Get an instance of MyModel with id=1
instance = MyModel.objects.get(id=1)
# Check if the instance exists
if MyModel.objects.filter(id=1).exists():
print("Instance exists")
else:
print("Instance does not exist")
In this example, get(id=1) returns an instance of MyModel with id=1. The exists() method is then called on the queryset MyModel.objects.filter(id=1) to check if the instance exists in the database. If it does, the message "Instance exists" is printed. Otherwise, the message "Instance does not exist" is printed.
原文地址: https://www.cveoy.top/t/topic/ZLR 著作权归作者所有。请勿转载和采集!