在 django 中,如何根据同一模型中的另一个字段限制一个外域的选择? [英] In django, how to limit choices of a foreignfield based on another field in the same model?

查看:17
本文介绍了在 django 中,如何根据同一模型中的另一个字段限制一个外域的选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些模型(我将字段数量限制为只需要的那些)

I have these models (I have limited the number of fields to just those needed)

class unit(models.Model):
    name = models.CharField(max_length=200)

class project(models.Model):
    name = models.CharField(max_length=200)

class location(address):
    project = models.ForeignKey(project)

class project_unit(models.Model):
    project = models.ForeignKey(project)         
    unit = models.ForeignKey(unit)

class location_unit(models.Model):
    project = models.ForeignKey(project)    
      #Limit the selection of locations based on which project has been selected
    location = models.ForeignKey(location)
      #The same here for unit. But I have no idea how.
    unit = models.ForeignKey(project_unit)       

我的新手头无法掌握如何在 location_unit 模型中限制 location 和 unit 这两个字段以仅显示引用 location_unit 中所选项目的选项.我应该覆盖模型表单并在那里进行查询,还是可以使用limit_choices_to.无论哪种方式,我都失败了

My newbie head just cannot grasp how to limit the two fields, location and unit, in the location_unit model to only show the choices which refers to the selected project in location_unit. Should I override the modelform and make a query there or can I use the limit_choices_to. Either way I have failed trying both

澄清一下,我希望这发生在 Django Admin 中.我也试过 formfield_for_foreignkey,但还是不行.

Just to clarify, I want this to happen in the Django Admin. I have also tried formfield_for_foreignkey, but still a no go for me.

编辑 2:

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "unit":
        kwargs["queryset"] = project_unit.objects.filter(project=1)
        return db_field.formfield(**kwargs)
    return super(location_unit_admin, self).formfield_for_foreignkey(db_field, request, **kwargs)

上面的代码片段有效.但我当然不希望项目指向 1.我如何引用模型 project_id?我试过这个:

The above code snippet works. But of course I don't want the project to point to 1. How do I reference to the models project_id? I tried this:

kwargs["queryset"] = project_unit.objects.filter(project=self.model.project.project_id)

但这不起作用(实际上我已经尝试了很多变体,是的,我是 django 新手)

But that doesn't work (actually I have tried a lot of variations, yes I am a django newbie)

推荐答案

这就是答案,太棒了:https://github.com/digi604/django-smart-selects

这篇关于在 django 中,如何根据同一模型中的另一个字段限制一个外域的选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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