select_related
我希望能够通过使用or来检查是否已经获取了相关对象prefetch_related
,以便我可以相应地序列化数据。这是一个例子:
class Address(models.Model):
street = models.CharField(max_length=100)
zip = models.CharField(max_length=10)
class Person(models.Model):
name = models.CharField(max_length=20)
address = models.ForeignKey(Address)
def serialize_address(address):
return {
"id": address.id,
"street": address.street,
"zip": address.zip
}
def serialize_person(person):
result = {
"id": person.id,
"name": person.name
}
if is_fetched(person.address):
result["address"] = serialize_address(person.address)
else:
result["address"] = None
######
person_a = Person.objects.select_related("address").get(id=1)
person_b = Person.objects.get(id=2)
serialize_person(person_a) #should be object with id, name and address
serialize_person(person_b) #should be object with only id and name
在这个例子中,这个函数is_fetched
就是我要找的。我想确定 person 对象是否已经有一个解析地址,如果有,它也应该被序列化。但如果没有,则不应执行进一步的数据库查询。
那么有没有办法在 Django 中实现这一点?