Valter Silva
Valter Silva

Reputation: 16656

How to use foreign key to get related objects?

I have a person which could have many images. I would like to use like this: person.image[x].image to retrieve my image address. How can I associate using foreign key a person with their images ? And access their images using a person object ?

class Person(models.Model):
    user = OneToOneField(User, on_delete=models.CASCADE)
    gender = CharField(max_length=1, choices=GenderChoices, blank=True, null=True)
    birth_date = DateField(blank=True, null=True)

    def __unicode__(self):
        return self.user.username

class Image(models.Model):
    person = ForeignKey(Person)
    itype = CharField(max_length=1, choices=ImageChoices)
    image = ImageField(upload_to=image_path, blank=True, null=True)
    created = DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.image.path

Upvotes: 0

Views: 48

Answers (1)

bakkal
bakkal

Reputation: 55448

person.image_set.all() is one way, and if needed you can also filter through the images of a person for a given query, e.g. persom.image_set.filter(...), and if you just want the count, person.image_set.count()

You can read more on how to query for related objects here: https://docs.djangoproject.com/en/1.8/topics/db/queries/#related-objects

Upvotes: 1

Related Questions