I have a question whether the code is acceptable, or is there another possibility with a more optimal way out of this situation My one model look like that:
class ModelA(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
manga = models.ManyToManyField(Manga, through='ModelB')
def manga_list(self):
return ModelB.objects.filter(user=self.pk).all()
def manga_list_reading(self):
return ModelB.objects.filter(user=self.pk, type=utils.READING).all()
and second model look like that:
class ModelB(models.Model):
user = models.ForeignKey(ModelA, on_delete=models.CASCADE, )
manga = models.ForeignKey(Manga, on_delete=models.CASCADE)
type = models.CharField(max_length=30, choices=utils.LIST_PROFILE_CHOICES, null=False, blank=False)
so my question is about this def list return, is it some another option for do it ?
CodePudding user response:
Your manga_list
can be queried with:
self.modelb_set.all() # ModelB objects
It thus does not make much sense to specify a method for this, since you can query this with my_model_a.modelb_set.all()
. Furthermore naming this manga_list
is a bit "misleading", since the queryset will return ModelB
objects, not Manga
objects. If you want to return all Manga
objects linked by the ModelB
, you can do this with:
my_model_a.manga.all() # Manga objects
If you want to retrieve the Manga
objects for which the type is READING
, you can retrieve these with:
my_model_a.manga.filter(modelb__type=utils.READING) # Manga objects