简体   繁体   中英

Django use dynamic choices in model by foreignkey

I have a model; for concern to this question it matters two field one is foreignkey to other model Plan and other is choicefield as shown below:

class MyModel(models.Model):
    CHOICES = (
        (1, 'A1'),
        (2, 'A2'),
        (3, 'B1'),
        (4, 'B2'),
    )
    category = models.IntegerField(choices=CHOICES, default=3)
    has_plan = models.ForeignKey(Plan, on_delete=models.CASCADE)

Below is my Plan model:

class Plan(models.Model):
    PLAN_CHOICES = [(1, "Individual"), (2, "Company")]
    plan_name = models.IntegerField(choices=PLAN_CHOICES, default=2)
    plan_validity = models.IntegerField(default=180, help_text="Days after plan expires")

I want to update CHOICES which are to be available in category field of MyModel depending on selection of has_plan . Consider if has_plan points to Plan object with plan_name ; (2, "Company") then CHOICES are to be updated to:

CHOICES = (
        (1, 'A1'),
        (2, 'A2'),
        (3, 'A3'),
        (4, 'B1'),
        (5, 'B2'),
    )

I can achieve this in views with help of form fields but in that case I have to handle it for view and admin both hence I am looking for a better and simpler way to achieve this.

I am able to raise error with clean() method in model but I want to update CHOICES instead of just raising an exception.


Update:

While creation of first entry I have set up multi-part form and achieved the solution for creation, but for editing in Django Admin, custom view and it seems that I have to handle both separately. Instead of doing that I want a way so that I can update it once so that for create and edit in either django admin or custom view I just have to override single method.

If you want it to be interactive (ie when user changes has_plan in UI, category available choices change) you need to implement some client side logic. If its the case I suggest that you to just add a clean method to your model to check correctness of category , has_plan pair. clean method will be called in Django admin model forms too.

Update question/comment if somehow has_plan has a fixed value and you need another solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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