P
P
paevlk20072014-06-14 00:34:40
Django
paevlk2007, 2014-06-14 00:34:40

Django filtering ForeignKey

Good afternoon!
models.py

class Delivery(models.Model):
    created_on = models.DateTimeField(u"Дата создания", auto_now_add=True)
    datedelivery = models.DateField(u"Дата отгрузки")
    dateofperformance = models.DateTimeField(u"Дата исполнения")
    partner = models.ForeignKey(Partner, verbose_name=u"Контрагент")

КОНТРАГЕНТЫ:
class Partner(models.Model):
    name = models.CharField(max_length=100)
    created_on = models.DateTimeField(auto_now_add=True)

FILTER REQUIRED: Delivery -> Partner in - Delivery:
forms.py
class DeliveryForm(forms.ModelForm):
    partner = forms.ModelChoiceField(label='Контрагент', queryset=Delivery.objects.all())

Gives a list of counterparties that were used in Delivery, but they are duplicated, counterparties are not unique... like
Контрагента1
Контрагента1
Контрагента2
Контрагента1
Контрагента3
Контрагента4
Контрагента2
Контрагента5

forms.py
class DeliveryForm(forms.ModelForm):
    partner = forms.ModelChoiceField(queryset=Delivery.objects.filter().values_list('partner', flat=True).order_by('partner').distinct())

Result: Returns all Unique Accounts in Delivery, but only their id, there is no name field.
We were advised to pass an additional parameter to the form constructor, in your case the partner ID and filter by it. How to do it, I don't know.
There are options?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yttrium, 2014-06-14
@yttrium

Contractors are unique, only it should not be "queryset=Delivery.objects.all()" but "queryset=Partner.objects.all()"
But to be honest, the second forms.py ala Frankenstein suggests that you need to somehow agree on what is FILTER REQUIRED"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question