简体   繁体   中英

How to exclude some query from inline Django admin model?

Django 2.0.3 , Python 3.6.1 .

I try to filter QuerySet of ForeignKey field on inline admin model (Django Admin).

# ./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
    ]

How to exclude from PriceInlineAdmin QuerySet colours with name blue ?

I would try to do it this way

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM