Django外键下拉过滤器

时间:2017-05-07 16:46:34

标签: python django

我有一个名为Listing的模型,它基本上是我的用户发布的工作列表。其中一个字段是名为Address的外键(因为用户可以有多个地址)。这是我的models.py:

class JobListing(models.Model):
    title = models.CharField(max_length=250)
    description = models.TextField()
    customer = models.ForeignKey('CustomerAuth.CustomerProfile')
    address = models.ForeignKey('CustomerAuth.Address')

这是我的forms.py:

class JobListingForm(forms.ModelForm):
    class Meta:
        model = JobListing
        fields = ['title', 'description', 'address', 'customer']

最后是我的views.py的相关部分:

def create_listing(request):
    form = JobListingForm(request.POST or None)

    if form.is_valid():
        listing = form.save(commit=False)
        listing.save()

        current_user = CustomerProfile.objects.get(user=request.user)
        listing.customer = current_user
        listing.save()

        return HttpResponseRedirect('/listings/id/%s' % listing.id)

    context_dict = {'form': form}
    return render(request, 'listing/create-listing.html', context_dict)

目前,当用户从下拉列表中选择一个地址时,它会显示每个人的地址。无论如何我可以过滤它,以便只显示该用户输入的地址。

2 个答案:

答案 0 :(得分:1)

尝试这样的事情

model1.objects.get(pk=1).model2_set.all() 

答案 1 :(得分:1)

forms.py

class JobListingForm(forms.ModelForm):
    class Meta:
        model = JobListing
        fields = ['title', 'description', 'address', 'customer']

    def __init__(self, user, *args, **kwargs):
    super(JobListingForm, self).__init__(*args, **kwargs)
    self.fields['address'].queryset = Address.objects.filter(user=user)

在您的观看文件中

def create_listing(request):
    user = request.user
    form = JobListingForm(user, request.POST or None) #pass request.user