检查对象是否是Django中ManyToMany关系的一部分的最佳做法是什么

时间:2022-02-16 20:06:55

from an instance of Site with a ManyToMany relationship to Kiosk, i'd like to check if a Kiosk object is part of the relationship.

从具有ManyToMany关系的站点实例到Kiosk,我想检查Kiosk对象是否是关系的一部分。

I could do

我可以

self.apps.get(id=app_id).exists() and check if True

or

self.apps.get(id=app_id) and catch the ObjectDoesNotExist error

or

self.apps.filter(id=app_id) and check if True
  • If I have to catch a possible ObjectDoesNotExist error, I may as well use the second one
  • 如果我必须捕获可能的ObjectDoesNotExist错误,我也可以使用第二个错误

  • I can do the second but doesnt seem super clean
  • 我可以做第二次但看起来并不干净

  • can use the third one but using filter on a unique ID seems wrong to me
  • 可以使用第三个,但在唯一ID上使用过滤器似乎对我不对

You can tell me to use whatever works and that'll be a valid answer ;-)

你可以告诉我使用任何有用的东西,这将是一个有效的答案;-)

1 个解决方案

#1


10  

I would use

我会用

self.apps.filter(id=app_id).exists()

What's wrong with that?

这有什么问题?

#1


10  

I would use

我会用

self.apps.filter(id=app_id).exists()

What's wrong with that?

这有什么问题?