我想使用Django 過濾器 從我的個人資料模型中過濾用戶的名字,
這是我在models.py 中的個人資料模型。
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
total_members = models.CharField(max_length=500, blank=True)
...other fields
這是我的filters.py
import django_filters
from .models import Profile
class ProfileFilter(django_filters.FilterSet):
class Meta:
model = Profile
fields = '__all__'
在這種情況下,當我將表單添加到模板時,它為我提供了帶有所有用戶用戶名的選擇標籤,我不希望這樣,因為如果用戶想按用戶名過濾用戶,那麼他們可以按用戶名進行搜索,而不是在下拉列表中查找。
請幫我 (:
我得到了解決方案,我剛剛在我的 Django 過濾器表單中添加了一個文件,並通過Double Underscore (Name Mangling) 訪問相關文件,user__first_name
這是我代碼的更改版本
import django_filters
from .models import Profile
class ProfileFilter(django_filters.FilterSet):
first_name = django_filters.CharFilter(
label="First Name",
field_name="user__first_name",
lookup_expr='icontains',
widget=forms.TextInput(attrs={
'placeholder': 'First Name',
'class': 'form-control',
'type': 'text'
})
)
class Meta:
model = Profile
fields = ['first_name', ...other fields]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句