In my project, there are three models:
class Level1(models.Model):
name = models.CharField(max_length=250)
class Level2(models.Model):
name = models.CharField(max_length=250)
level1 = models.ForeignKey(Level1, on_delete=models.RESTRICT)
class Level3(models.Model):
name = models.CharField(max_length=250)
level2 = models.ForeignKey(Level2, on_delete=models.RESTRICT)
Level1 model has 2 objects WA
, TX
. Level2 has 5 objects AAA
, BBB
where the foreign key is WA
; and AAA
, CCC
, DDD
where the foreign key is TX
.
In Level3, I want to add an object RRRR
where the Level2 foreign key object is AAA
.
When I tried to fetch the Level2 by Level2.objects.get(name='AAA')
, it shows error get() returned more than one Level2 -- it returned 2!
How to solve this issue. Thanks in advance.
Alhamdulillah, finally I solve the issue by combining filter and get.
Level2.objects.filter(level1__name='WA').get(name='AAA')