Django 2.0.3
,Python 3.6.1
。
我尝试在内联管理模型(Django Admin)上过滤ForeignKey字段的QuerySet。
# ./app/models.py
class Product(models.Model):
name = models.CharField(max_length=255)
class Color(models.Model):
name = models.CharField(max_length=255)
class Price(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
color = models.ForeignKey(Color, on_delete=models.CASCADE)
price = models.PositiveSmallIntegerField()
# ./app/admin.py
class PriceInlineAdmin(admin.TabularInline):
model = Price
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ('id',)
inlines = [
PriceInlineAdmin
]
如何从名为PriceInlineAdmin
的{{1}} QuerySet颜色中排除?
答案 0 :(得分:1)
我会尝试这样做
class PriceInlineAdmin(admin.TabularInline):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "name":
kwargs["queryset"] = Price.objects.exclude(color__name="blue")
return super().formfield_for_foreignkey(db_field, request, **kwargs)