开发者

What's best practice to check if an object is part of a ManyToMany relationship in Django

开发者 https://www.devze.com 2022-12-22 20:04 出处:网络
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.

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.

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 Objec开发者_如何学CtDoesNotExist error, I may as well use the second one
  • 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

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


I would use

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

What's wrong with that?

0

精彩评论

暂无评论...
验证码 换一张
取 消