[英]Restrictive selection in django-admin panel
I have 3 simple models in my Django project as below: 我的Django项目中有3个简单的模型,如下所示:
class Customer(models.Model):
name = models.CharField(max_length=250)
class Location(models.Model):
name = models.CharField(max_length=500)
customer = models.ForeignKey(Customer)
class CustomerLocation(models.Model):
name = models.CharField(max_length=250)
customer = models.ForeignKey(Customer)
location = models.ForeignKey(Location)
Now, I want to display the list of location
(s) linked to a Customer
in CustomerLocation
in Admin panel. 现在,我想显示的列表
location
链接到一个(或多个) Customer
在CustomerLocation
在管理面板。
For eg, 例如
Customer = C1, Location for C1 = L1, L2.
Customer = C2, Location for C2 = L3.
If I select C1
as my Customer
, I should be able choose only L1, L2
in Location
. 如果我选择
C1
作为我的Customer
,则应该只能在Location
选择L1, L2
。 Else, it should be empty. 否则,它应该为空。
How can I achieve this restriction in Django-Admin? 如何在Django-Admin中实现此限制?
PS: I want to achieve this via models.Admin
only. PS:我想通过
models.Admin
来实现。
There is a pluggable django app for that: https://github.com/digi604/django-smart-selects 有一个可插入的django应用程序: https : //github.com/digi604/django-smart-selects
You just add a field: 您只需添加一个字段:
location = ChainedForeignKey(
'Location',
chained_field='customer',
chained_model_field='customer',
auto_choose=True,
null=True,
blank=True,
)
(Not tested, but should work.) (未经测试,但应该可以使用。)
And in Django admin, if you change Customer
, Locations
list changes accordingly. 在Django admin中,如果您更改
Customer
,则Locations
列表也会相应更改。
UPD. UPD。 Hm, it appears that I didn't understand your question properly.
嗯,看来我不太了解您的问题。
What do you need Customer
field in your Location
model for? 您在
Location
模型中需要“ Customer
字段做什么? As far as I can see, CustomerLocation
is responsible for linking these two models with one another, and every Customer
may be thus linked to multiple Locations
. 据我所知,
CustomerLocation
负责将这两个模型相互链接,因此每个Customer
都可以链接到多个Locations
。 You can achieve this with a ManyToManyField
more easily, by the way. 顺便说一下,您可以使用
ManyToManyField
轻松实现此目的。
Why do you need to display customers and locations at CustomerLocation
? 为什么需要在
CustomerLocation
显示客户和位置? You probably can use Django filters for that. 您可能可以为此使用Django过滤器。 For example:
例如:
class CustomerLocationAdmin(admin.ModelAdmin): list_display = ('customer', 'location') list_filter = ('location', 'customer') admin.register(CustomerLocation, CustomerLocationAdmin)
Then, you get: 然后,您得到:
Will this solution work for you? 该解决方案对您有用吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.