Django: follow the relationship back

Hey, I have models like this:

class Galleries(models.Model):
  creation_date = models.DateTimeField()
  name = models.CharField(max_length=255, unique=True)
  gallery_type = models.ForeignKey(Categories)

class Categories(models.Model):
  handle = models.CharField(max_length=255, unique=True)

class Values(models.Model):
  category = models.ForeignKey(Categories)
  language = models.CharField(max_length=7)
  category_name = models.CharField(max_length=50)

And now I just want to achieve category values, starting with the Gallery. For example: galleries = Galleries.objects.get(id=1). And now I want to somehow achieve the values ​​using this "gallery" object ... To get the values ​​with a specific language, it would be much better ... I miss the skills in Django ORM, so if you can, please point me some docs or give sample code. Thank!

+3
source share
2 answers
galleries = Galleries.objects.get(id=1)
values = galleries.gallery_type.values_set.filter(language='language')

Interestingly, you used the exact language that documents used to link to related searches. I have always believed that the definition is strange for the gut, perhaps because they put it in quotation marks.

""

http://docs.djangoproject.com/en/1.2/topics/db/queries/#following-relationships-backward

+5

select_related , , . select_related

gallery = Galleries.objects.select_related().get(id=1)

fk:

class Values(models.Model):
  category = models.ForeignKey(Categories, related_name="categories")
  language = models.CharField(max_length=7)
  category_name = models.CharField(max_length=50)

,

values = gallery.gallery_type.categories.filter(language="language")
+1

Source: https://habr.com/ru/post/1796666/


All Articles