简体   繁体   中英

How to define method to return related objects

I have two models:

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)

I want to access to pets over profile class. When I call profile.pets on terminal, the response is:

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

how to I get pets for a profile object?

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

profile.pets is a method.

You have to call it

pets = profile.pets()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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