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

查看:106
本文介绍了在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中引用所选项目的选项。我应该覆盖modelform并在那里查询,还是可以使用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管理中发生这种情况。我也试过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.如何引用model_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

This is the answer, it is brilliant: https://github.com/digi604/django-smart-selects

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

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