Django中的动态过滤器选择字段 [英] dynamic filter choice field in django

查看:71
本文介绍了Django中的动态过滤器选择字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 django-filter 来过滤页面上的结果.我可以使用像这样的静态选择过滤器:

I am using django-filter to filter results on a page. I am able to use static choice filters like this:

filters.py

filters.py

FILTER_CHOICES = (
('', 'All States'),
('AL', 'Alabama'),
('AK', 'Alaska'),
('AZ', 'Arizona'),
#and so forth, I am not going to list all 50 states for this a question on a forum
)


class SightingFilter(django_filters.FilterSet):
    state = django_filters.ChoiceFilter(choices=FILTER_CHOICES)
    class Meta:
        model = Sighting
        fields = ['city', 'store', 'brand', 'product', 'flavor', 'fat', 'size']   

因此上面的代码可以正常工作,但是如果我尝试在下面创建一个像"plant_number"这样的动态列表:

So that code above works fine, but if I try to make a dynamic list like "plant_number" below:

class SightingFilter(django_filters.FilterSet):
    state = django_filters.ChoiceFilter(choices=FILTER_CHOICES)
    plant_number = django_filters.ChoiceFilter(choices=[(o.plant_number, o.plant_number + " " + o.manufacturer_name) for o in Plant.objects.all()])
 class Meta:
        model = Sighting
        fields = ['city', 'store', 'brand', 'product', 'flavor', 'fat', 'size']

然后我得到了错误:

以10为底的int()无效文字:

invalid literal for int() with base 10:

它会在我的模板中突出显示此代码

and it highlights this code in my template

{% for obj in filter %}
    <a href="/sighting/{{ obj.slug }}/ ">{{ obj.date|date:"m/d/Y" }} {{ obj.brand }} ${{ obj.price|intcomma }} </a><br />
{% endfor %}

plant_number是模型中的CharField(工厂编号使用XX-XXX格式,其中X是数字).

The plant_number is a CharField in the model (plant numbers use the format XX-XXX, where the X's are digits).

我的视图如下:

def dashboard(request):
    if "Clear Filters" in request.GET:
        return redirect('/')
else:
    filter = SightingFilter(request.GET, queryset=Sighting.objects.all())
    context = {'filter': filter, 'request': request}
    return render_to_response('dashboard.html', context, context_instance=RequestContext(request))

感谢您的帮助!

编辑1/14/15

所以我可以肯定的是问题是plant_number是一个外键(抱歉,上面没有包含models.py).这就是为什么它期望一个int而不是一个字符串.因此,现在我需要弄清楚如何获取工厂编号的外键值,而不仅仅是工厂编号.我试过了:

So I am pretty certain the issue is that plant_number is a foreign key (sorry didn't include the models.py above). That is why it is expecting an int and not a string. So now I need to figure out how to get the foreign key value of the plant number instead of just the plant number. I tried:

plant_number = django_filters.ChoiceFilter(choices=[[o.plant_number.id, o.plant_number + " " + o.Manufacturer] for o in Plant.objects.all()])

也尝试过:

plant_number = django_filters.ChoiceFilter(choices=[[o.plant_number_id, o.plant_number + " " + o.Manufacturer] for o in Plant.objects.all()])

均无效.我得到的"unicode"对象在第一个对象上没有属性"id",而"Plant"对象在第二个对象上没有属性"plant_number_id".

Neither works. I get 'unicode' object has no attribute 'id' on the first one and 'Plant' object has no attribute 'plant_number_id' on the second.

models.py

models.py

class Sighting(models.Model):
    date = models.DateField(default=today)
    brand = models.CharField(max_length=200)
    product = models.CharField(max_length=200)
    flavor = models.CharField(max_length=200)
    fat = models.DecimalField(max_digits=4, decimal_places=2)
    size = models.DecimalField(max_digits=10, decimal_places=2)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    plant_number = models.ForeignKey('Plant', blank=True, null=True )
    store = models.CharField(max_length=200)
    city =  models.CharField(max_length=200)
    state = models.CharField(max_length=200, choices=STATE_CHOICES)
    photo = ProcessedImageField(upload_to=yogurtupload,
                                   processors=[ResizeToFit(600, 600)], #Resizes so the largest dimension is 600 (width or height, whichever hits 600 first)
                                   format='JPEG',
                                   options={'quality': 72})
    slug = models.SlugField(unique=True)

    def save(self):
        now = timestamp()
        forslug = str(now) + " " + str(self.plant_number) + " " + str(self.brand)
        self.slug = slugify(forslug)
        super(Sighting, self).save()

     def __unicode__(self):
        return self.slug

class Plant(models.Model):
    plant_number = models.CharField(max_length=200)
    Manufacturer = models.CharField(max_length=200)
    city = models.CharField(max_length=200)
    state = models.CharField(max_length=200, choices=STATE_CHOICES)
    slug = models.SlugField(unique=True)

    def save(self):
        self.slug = slugify(self.plant_number)
        super(Plant, self).save()

    def __unicode__(self):
        return self.slug

推荐答案

所以我弄清楚了,我正在传递 plant_number 而不是 id django期望如此,因为我的过滤器与Sightings模型相对,并且 plant_number 是Sightings模型中的外键.起作用的代码:

So I figured this out, I was passing the plant_number instead of the id, which is what django was expecting since my filter is against the Sightings model and plant_number is a foreign key in the the Sightings model. The code that worked:

plant_number = django_filters.ChoiceFilter(choices=[[o.id, o.plant_number + " " + o.Manufacturer] for o in Plant.objects.all().order_by('IMS_plant')])

这篇关于Django中的动态过滤器选择字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆