【问题标题】:Filtering Data Based On Foreign Key - Django基于外键过滤数据 - Django
【发布时间】:2019-10-08 02:19:48
【问题描述】:

我在根据之前选择的字段动态填充表单数据时遇到问题。就我而言,我有两种模型,其中一种包含与不同俱乐部相关的不同类型的会员资格。然后我有另一个模型来处理个别俱乐部的注册。

我的问题 - 当最终用户准备好注册时,表单呈现(我已经根据他们最初选择的俱乐部过滤掉了会员)但我需要根据选择的会员资格(外键)过滤价格播放器模型。

以下是我的会员类型模型:

存储俱乐部可用会员资格的模型,以便会员可以在注册页面上选择和付款

class ClubMemberships(models.Model):

club_id = models.ForeignKey(ClubInfo, on_delete=models.CASCADE)
title = models.CharField(max_length=30, default='')
price = models.DecimalField(default=0.00, max_digits=6, decimal_places=2)
description = models.TextField()

def __str__(self):
    return self.title

这是注册的模型:

存储用于会员注册的玩家信息的模型

class Player(models.Model):

club_id = models.ForeignKey(ClubInfo, on_delete=models.CASCADE)
membership_title = models.ForeignKey(ClubMemberships, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
dob = models.DateField(max_length=8)
email = models.EmailField(max_length=50)
phone = models.CharField(max_length=12)
mobile = models.CharField(max_length=15)
emergency_contact_name = models.CharField(max_length=40)
emergency_contact_mobile = models.CharField(max_length=15)
address1 = models.CharField(max_length=30)
address2 = models.CharField(max_length=30, default='')
address3 = models.CharField(max_length=30, default='')
town = models.CharField(max_length=30)
county = models.CharField(max_length=30)
country = models.CharField(max_length=30)

def __str__(self):
    return "%s %s" % (self.first_name, self.last_name)

选手报名表:

接受会员注册详情的表格

class PlayerRegistrationForm(forms.ModelForm):

class Meta:
    model = Player
    fields = '__all__'
    labels = {
        'dob': 'Date of Birth'
    }
    widgets = {
        'dob': forms.DateInput(attrs={'id': 'datepicker'})
    }

def __init__(self, *args, **kwargs):
    super(PlayerRegistrationForm, self).__init__(*args, **kwargs)
    self.fields['club_id'].widget = forms.HiddenInput()

def load_price(self, request):
    membership = request.GET.get('membership_title')
    title = ClubMemberships.objects.filter(title=membership)
    self.fields['price'].queryset = ClubMemberships.objects.filter(price=title.price)

load_price 是我正在尝试完成但无法使其正常工作的一个示例。我希望表单检查表单中选择的会员资格,然后过滤该会员资格的价格并将其显示在表单中。

这是我在浏览器中的表单:

Form

非常感谢任何帮助,因为在我能够正确显示价格之前,我无法合并 PayPal。

谢谢

【问题讨论】:

  • 您需要进行 ajax 调用,以便在选择会员类型时查询您的应用程序以获取可用价格
  • 任何有关如何执行此操作的特定文档,因为我在这里没有以前的经验
  • Player.objects.filter(club_id__clubinfocolumn='something') # 这会执行 sql 连接。你需要这个。

标签: python django forms model foreign-keys


【解决方案1】:

这是一个基于汽车制造商和型号的示例。

当制造商在下拉列表中发生更改时,此 javascript 正在寻找

$("#id_car_make").change(function () {
    var url = $("#searchForm").attr("data-models-url");  // get the url of the `load_cities` view
    var carMakeId = $(this).val();  // get the selected country ID from the HTML input

    $.ajax({                       // initialize an AJAX request
        url: url,                    // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
        data: {
            'car_make': carMakeId       // add the country id to the GET parameters
        },
        success: function (data) {   // `data` is the return of the `load_cities` view function
            $("#id_car_model").html(data);  // replace the contents of the city input with the data that came from the server
        }
    });

});

它调用这个 url

    path('ajax/load-models/', views.load_models, name="ajax_load_models"),

调用这个视图

def load_models(request):
    car_make_id = request.GET.get('car_make')
    car_models = CarModel.objects.filter(car_make_id=car_make_id).order_by('name')
    return render(request, 'leases/partials/car_model_dropdown_list_options.html', {'car_models': car_models})

使用此模板将模型下拉传递给 javascript

    <option value="">Model</option>
    {% for car_model in car_models %}
    <option value="{{ car_model.pk }}">{{ car_model.name }}</option>
    {% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2020-09-07
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 2013-09-05
    相关资源
    最近更新 更多