[英]Django models filter objects for ManyToManyField
For example I have a model:例如我有一个 model:
class User(models.Model):
is_active = models.BooleanField(
'Is active user?',
default=True
)
friends = models.ManyToManyField(
'self',
default=None,
blank=True,
)
How can I filter only active users in ManyToManyField?如何仅过滤 ManyToManyField 中的活跃用户? (It won't work, just my ideas, ManyToManyField need Model in to=)
(行不通,只是我的想法,ManyToManyField需要Model in to=)
queryset = User.objects.filter(is_active=True)
friends = models.ManyToManyField(
queryset,
default=None,
blank=True,
)
You can work with limit_choices_to=…
[Django-doc] to limit the choices of adding an element to a ManyToManyField
, so here you can implement this as:您可以使用
limit_choices_to=…
[Django-doc]来限制将元素添加到ManyToManyField
的选择,因此在这里您可以将其实现为:
class User(models.Model):
is_active = models.BooleanField(
'Is active user?',
default=True
)
friends = models.ManyToManyField(
'self',
limit_choices_to={'is_active': True}
)
This will filter the set of available User
s in a ModelForm
that you construct for that model, and in the ModelAdmin
for that model.这将过滤您为该 model 构建的 ModelForm 中的可用
User
集合,以及为该ModelAdmin
构建的ModelForm
中的一组可用 User 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.