V
V
Vic Shostak2018-03-10 20:34:06
Django
Vic Shostak, 2018-03-10 20:34:06

Django. How to exclude the required values ​​from FK fields of an inline model?

Greetings.

Django 2.0.3, Python 3.6.1.

Can you please tell me how to exclude (make a filter) the necessary values ​​from the QuerySet field of the inline model?
Here is my code:
# ./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
    ]

Actually, how in the inline model PriceInlineAdmin to exclude from the field color(which is displayed as select , because ForeignKey ) the entry with the value blue?
I'll be glad for good advice.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-03-10
@vikkyshostak

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)

A
Alexey Petrov, 2018-03-10
@Dragmar

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 question

Ask a Question

731 491 924 answers to any question