Answer the question
In order to leave comments, you need to log in
Django. How to exclude the required values from FK fields of an inline model?
Greetings.
Django 2.0.3, Python 3.6.1.
# ./app/models.py
class Product(models.Model):
name = models.CharField(max_length=255)
class Color(models.Model):
name = models.CharField(max_length=255) # ['blue', 'red', 'yellow'] для примера
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
]
color
(which is displayed as select , because ForeignKey ) the entry with the value blue
? Answer the question
In order to leave comments, you need to log in
From documentation :
class PriceInlineAdmin(admin.TabularInline):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'color':
kwargs['queryset'] = Color.objects.all().exclude(name='blue')
return super().formfield_for_foreignkey(db_field, request, **kwargs)
Add a form to the PriceInlineAdmin
class .
In the form class:
def __init__(self, *args, **kwargs):
super(PriceForm, self).__init__(*args, **kwargs)
self.fields['color'].queryset = Color.objects.filter(~Q(name="blue"))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question