[英]Get objects that are not in manytomany relationship of a different model?
假設我有兩個模型和一個表單:
class Person(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
class Car(models.Model):
plate = models.CharField(max_length=255)
persons = models.ManyToManyField(Person)
class CarAddForm(forms.ModelForm):
plate = forms.CharField()
persons = forms.ModelMultipleChoiceField(queryset=Person.objects.all())
class Meta:
model = Car
fields = [
'plate',
'persons'
]
有沒有辦法獲取與任何汽車無關的人的 ModelMultipleChoiceField 查詢集? 在編輯 Car model object 的情況下,查詢集應包含與任何汽車無關的人員以及與正在編輯的汽車相關聯的人員
PS:也許有更好的方法來實現這一點?
您可以使用ManyToManyField
的limit_choices_to
--(Doc)參數作為
class Car(models.Model):
plate = models.CharField(max_length=255)
persons = models.ManyToManyField(
Person,
limit_choices_to={"car__isnull": True}
)
或者,您也可以將ModelMultipleChoiceField
的queryset
參數更改為
class CarAddForm(forms.ModelForm):
plate = forms.CharField()
persons = forms.ModelMultipleChoiceField(
queryset=Person.objects.filter(car__isnull=True)
)
class Meta:
model = Car
fields = [
'plate',
'persons'
]
您可以為查詢指定過濾器:
from django.db import models
class CarAddForm(forms.ModelForm):
...
persons = forms.ModelMultipleChoiceField(
queryset=Person.objects\
.annotate(car_count=models.Count('cars'))\
.filter(car_count=0))
...
另一種選擇是覆蓋 forms __init__()
方法。 也許是這樣的:
from django.db import models
class CarAddForm(forms.ModelForm):
...
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['person'].queryset = self.fields['person'].queryset\
.annotate(car_count=models.Count('cars'))\
.filter(car_count=0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.