python
1Entry.objects.filter(blog__name='Beatles Blog')
のように関連する項目を取ることができます
python
1class Year(models.Model): 2 year = models.PositiveIntegerField( 3 validators=[ 4 MinValueValidator(1900), 5 MaxValueValidator(datetime.now().year)], 6 help_text="Use the following format: <YYYY>", 7 unique=True) 8 created = CreationDateTimeField() 9 modified = ModificationDateTimeField() 10 11 def __str__(self): 12 return f"{self.year}" 13 14 15class Month(models.Model): 16 year = models.ForeignKey(Year, on_delete=models.CASCADE, 17 blank=True, null=True, db_index=True) 18 month = models.PositiveIntegerField( 19 validators=[ 20 MinValueValidator(1), 21 MaxValueValidator(12)], 22 help_text="Use the following format: <MM>") 23 created = CreationDateTimeField() 24 modified = ModificationDateTimeField() 25 26 def __str__(self): 27 return f"{self.year} {self.month}" 28 29 class Meta: 30 unique_together = (("year", "month"),)
実際に次のコードで取得が可能です。
python
1Month.objects.get(month=1, year__year=2017)
ただこうするとどんどんリンク先が深くなるので、例えばこのテーブルに「day」を追加したら
python
1Day.objects.get(day=1, month__month=1, month__year__year=2017)
とどんどん深くなっていってしまいます、テーブルの設計が悪いのかもしれませんが、ショートカットするいい方法はないでしょうか
あなたの回答
tips
プレビュー