inline parent value

17 views
Skip to first unread message

Roberto Russi

unread,
Dec 1, 2016, 12:12:15 PM12/1/16
to Django users
hi, I have 3 models:

class Orders(models.Model):
        brand = models.ForeignKey(
            Brands,
            verbose_name = "Brand",
            null=True,
            blank=True,
            related_name="ord_brand"
        )
        dateord = models.DateField("Date")
        numbord = models.CharField("Number",
            max_length=20,
            unique_for_year="dateord", 
        )

class OrderRows(models.Model):
        order = models.ForeignKey(
            Orders,
            verbose_name = "Order",
        )
        product = models.ForeignKey(
            Products,
            verbose_name = "Product",
        )
        price = models.DecimalField("Price",
            max_digits = 11,
            decimal_places=2,
        )

class Products(models.Model):
        brand = models.ForeignKey(
            Brands,
            verbose_name = "Brand",
        )
        code = models.CharField("Code",
            max_length=25, 
        )
        descr = models.CharField("Description",
            max_length=50, 
        )
        
In my admin.py I have a ModelForm for Orders and an Inline for OrderRow.
In the Inline I need filter product queryset for records where brand=orders.brand.

How can I do it?

Nate Granatir

unread,
Dec 11, 2016, 12:34:17 AM12/11/16
to Django users
You should be able to customize the queryset of any form by overriding it in the init method of the form. In this case, it's a little trickier because you'll need a custom admin and custom form for the inline. I haven't been able to test this, but I think you'll need to do the following.

In forms.py, add a custom inline form, and in the init method customize the queryset to whatever it needs to be, after calling super, e.g.:

class OrderRowsInlineForm(forms.ModelForm):
class Meta:
model = None
fields = '__all__'

def __init__(self, *args, **kwargs):
super(OrderRowsInlineForm, self).__init__(*args, **kwargs)
self.fields['product'].queryset = Product.objects.filter(brand='whatever')


Then in admin.py, import the form and add a custom admin for the inline that uses that custom form, like:

from forms import OrderRowsInlineForm

class OrderRowsInline(admin.TabularInline):
model = OrderRows
form = OrderRowsInlineForm


Now, depending on what you want to set the queryset to, you might run into some trouble; if the list of brands for an order row depends on the brand in the product, you might have to do some trickery to pass the proper brand (or brand id) down into the form. You can generally use self.instance, but if these are new records that haven't been saved yet (i.e. the user will be filling in the details and clicking Save), which i assume is true, then i believe self.instance is None until saved, so won't be useful here.

Reply all
Reply to author
Forward
0 new messages