Django,在查找中仅显示匹配条件

时间:2017-07-22 04:15:18

标签: django foreign-keys filtering

我在人员应用中有一个模型,比如这个,

class Crew(models.Model):
    nik = models.CharField(max_length=20)
    name = models.CharField(max_length=30)
    phone = models.CharField(max_length=20)
    isActive = models.NullBooleanField(verbose_name='Active')

class Meta:
    ordering = ('name',)

def __str__(self):
    return self.name

我也在车辆应用程序中创建模型,如下所示:

from personnel.models import Crew

class Vehicle(models.Model):
    plateNumber = models.CharField(max_length=10)
    regDate = models.DateField(verbose_name='Date')
    driver = models.ForeignKey(Crew, on_delete=models.CASCADE)

def __str__(self):
    return self.plateNumber

现在我想得到驱动程序列表,其中isActive = True在我的查找中。我怎么能这样做?

这就是我的意思:

Image

1 个答案:

答案 0 :(得分:2)

您需要在自己的应用中自定义管理部分。

class VehicleAdmin(admin.ModelAdmin):                                                                                               
    def formfield_for_foreignkey(self, db_field, request, **kwargs):                                                                
        if db_field.name == "driver":                                                                                               
            kwargs["queryset"] = Crew.objects.filter(isActive=True)                                                                 
        return super(VehicleAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)                                      


admin.site.register(Vehicle, VehicleAdmin) 

https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey