Django ForeignKey limit_choices_to一个不同的ForeignKey ID [英] Django ForeignKey limit_choices_to a different ForeignKey id

查看:237
本文介绍了Django ForeignKey limit_choices_to一个不同的ForeignKey ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用limit_choices_to限制ForeignKey的Django Admin选择,但我不知道该如何正确地进行操作。



此代码可以执行什么操作我想要类别ID为16,但是我不知道如何使用当前类别ID而不是对其进行硬编码。

  class MovieCategory(models.Model):
category = models.ForeignKey(Category)
movie = models.ForeignKey(Movie)
prefix = models.ForeignKey('Prefix', limit_choices_to = {'category_id':'16'},
blank = True,null = True)
number = models.DecimalField(verbose_name ='电影编号',max_digits = 2,
空白= True,null = True,decimal_places = 0)

是否可以引用

解决方案

经过半小时的阅读,我终于弄清楚了。



你不能如果以我尝试的方式引用模型,则无法使django以我想要使用limit_choices_to的方式进行操作,因为它无法在同一模型中找到其他ForeignKey的ID。



如果您改变django的工作方式,显然可以做到这一点,但是解决此问题的一种更简单的方法是改为对admin.py进行更改。



这是我的models.py中的外观:

 #models.py 
类MovieCategory (models.Model):
category = models.ForeignKey(Category)
movie = models.ForeignKey(Movie)
prefix = models.ForeignKey('Prefix',blank = True,null = True)
number = models.DecimalField(verbose_name ='电影编号',max_digits = 2,
blank = True,null = True,decimal_places = 0)

我只是完全删除了limit_choices_to。
我在此处发现了类似的问题解决方案由Kyle Duncan发布。
的区别在于,它使用的是ManyToMany而不是ForeignKey。这意味着我必须在我的类 MovieCategoryAdmin(admin.ModelAdmin):下删除 filter_horizo​​ntal =('prefix',)



在admin.py中,我必须从django导入表单中添加 顶部创建一个表单。
表单外观如下:

  class MovieCategoryForm(forms.ModelForm):

类元:
模型= MovieCategory
字段= ['prefix']

def __init __(self,* args,** kwargs):
super(MovieCategoryForm ,self).__ init __(* args,** kwargs)
self.fields ['prefix']。queryset = Prefix.objects.filter(
category_id = self.instance.category.id)

我的AdminModel:

  class MovieCategoryAdmin(admin.ModelAdmin):

电影类别的管理类。

字段集= [
('Category',{'fields':['category']}),
('Movie',{'fields':['movie']}),
('Prefix',{ 'fields':['prefix']}),
('Number',{'fields':['number']}),
]
list_display =('category', '电影','前缀','数字')
s earch_fields = ['category__category_name','movie__title','prefix__prefix']
表格= MovieCategoryForm

这正是Kyle在他的答案中的描述方式,除了我必须在表单中添加 fields = ['prefix'] 否则它不会运行。如果您按照他的步骤进行操作,并记得删除filter_horizo​​ntal并添加您正在使用的字段,则应该可以使用。一项新条目,因为它在不退出时无法搜索类别ID。我正在尝试找出解决方法。


I'm trying to limit Django Admin choices of a ForeignKey using limit_choices_to, but I can't figure out how to do it properly.

This code does what I want if the category id is 16, but I can't figure out how to use the current category id rather than hard-coding it.

class MovieCategory(models.Model):    
    category = models.ForeignKey(Category)
    movie = models.ForeignKey(Movie)
    prefix = models.ForeignKey('Prefix', limit_choices_to={'category_id': '16'},
                               blank=True, null=True)
    number = models.DecimalField(verbose_name='Movie Number', max_digits=2,
                                 blank=True, null=True, decimal_places=0)

Is it possible to refer to the id of the category ForeignKey somehow?

解决方案

After hours of reading semi related questions I finally figured this out.

You can't self reference a Model the way I was trying to do so there is no way to make django act the way I wanted using limit_choices_to because it can't find the id of a different ForeignKey in the same model.

This can apparently be done if you change the way django works, but a simpler way to solve this was to make changes to admin.py instead.

Here is what this looks like in my models.py now:

# models.py
class MovieCategory(models.Model):    
    category = models.ForeignKey(Category)
    movie = models.ForeignKey(Movie)
    prefix = models.ForeignKey('Prefix', blank=True, null=True)
    number = models.DecimalField(verbose_name='Movie Number', max_digits=2,
                                 blank=True, null=True, decimal_places=0)

I simply removed limit_choices_to entirely. I found a similar problem here with the solution posted by Kyle Duncan. The difference though is that this uses ManyToMany and not ForeignKey. That means I had to remove filter_horizontal = ('prefix',) under my class MovieCategoryAdmin(admin.ModelAdmin): as that is only for ManyToMany fields.

In admin.py I had to add from django import forms at the top to create a form. This is how the form looks:

class MovieCategoryForm(forms.ModelForm):

    class Meta:
        model = MovieCategory
        fields = ['prefix']

    def __init__(self, *args, **kwargs):
        super(MovieCategoryForm, self).__init__(*args, **kwargs)
        self.fields['prefix'].queryset = Prefix.objects.filter(
                                        category_id=self.instance.category.id)

And my AdminModel:

class MovieCategoryAdmin(admin.ModelAdmin):
    """
    Admin Class for 'Movie Category'.
    """
    fieldsets = [
        ('Category',      {'fields': ['category']}),
        ('Movie',         {'fields': ['movie']}),
        ('Prefix',        {'fields': ['prefix']}),
        ('Number',        {'fields': ['number']}),
    ]
    list_display = ('category', 'movie', 'prefix', 'number')
    search_fields = ['category__category_name', 'movie__title', 'prefix__prefix']
    form = MovieCategoryForm

This is exactly how Kyle describes it in his answer, except I had to add fields = ['prefix'] to the Form or it wouldn't run. If you follow his steps and remember to remove filter_horizontal and add the fields you're using it should work.

Edit: This solution works fine when editing, but not when creating a new entry because it can't search for the category id when one doesn't exits. I am trying to figure out how to solve this.

这篇关于Django ForeignKey limit_choices_to一个不同的ForeignKey ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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