简体   繁体   English

在django-admin面板中进行限制性选择

[英]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链接到一个(或多个) CustomerCustomerLocation在管理面板。

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. 嗯,看来我不太了解您的问题。

  1. 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轻松实现此目的。

  2. 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: 然后,您得到:

  1. A list of customers and locations 客户和位置列表
  2. Two dropdowns for customer and location. 客户和位置的两个下拉菜单。 You select particular customer or a particular location to get necessary data. 您选择特定的客户或特定的位置以获取必要的数据。

Will this solution work for you? 该解决方案对您有用吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM