繁体   English   中英

如何定义返回相关对象的方法

[英]How to define method to return related objects

我有两个模型:

class Profile(models.Model):
    user = models.OneToOneField(User, null=True)
    address = models.CharField(max_length=500)

    def pets(self):
        return Pet.objects.filter(owner=self.id)

class Pet(models.Model):
    owner = models.ForeignKey(Profile)
    name = models.CharField(max_length=150)

我想通过个人资料课程访问宠物。 当我在终端上调用profile.pets时,响应为:

 <bound method Profile.pets of <Profile: sefa>

如何获取个人资料对象的宠物?

profile = Profile.objects.get(id=id_of_profile_you_want)
list_of_pets = profile.pet_set

profile.pets是一种方法。

你必须叫它

pets = profile.pets()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM