繁体   English   中英

Django-已从另一个模型中选择的模型选择

[英]Django - Model choices from another model's choices that are already selected

因此,我有一个模型AdminChoices ,该模型具有ManytoMany字段,该字段从另一个模型choices 我想要另一个具有ManytoMany字段的模型,他的选择只是AdminChoices的选定选择。 这是模型的当前代码。

class choices(models.Model):
    choices = models.CharField(max_length=300)

    def __str__(self):
        return self.choices

class AdminChoices(models.Model):
    choice1 = models.ManytoManyFields(choices, related_name="adminchoices_choice1_related")
    choice2 = models.ManytoManyFields(choices, related_name="adminchoices_choice2_related")
    etc

class UserChoices(models.Model):
    choice1 = "choice that can only be chosen from selected AdminChoices choice1"
    choice2 = "AdminChoices choice2"
    etc

我正在开发一个应用程序,用户可以在其中创建硬件配置。 此模型中的一个字段代表一个插槽,并且只能为该插槽选择一个选项。 这些选择必须首先由管理员批准,以确保广告位可以接受该选择。 这是AdminChoices模型进入的地方,管理员将可以访问全局管理配置,该配置批准一个插槽的选择,然后允许用户在其个人配置中选择一个已批准的选择。

我不确定是否要采用正确的方法,如何制作此模型?

请注意,这不是一个人可能想到的容易的任务。 实现此目的的最简单方法是重新构建数据库,如下所示:

class Choice(models.Model):
    choice = models.CharField(max_length=300)

    def __str__(self):
        return self.choice

class User(models.Model):
    username=models.CharField(max_length=300)

class SlotChoice(models.Model):
    slotname=models.CharField(max_length=300)
    choice = models.ForeignKey(Choice, related_name="adminchoices_related")
    def __str__(self):
        return self.slotname + " " +self.choice.choice

class UserChoice(models.Model):
    user = models.ForeignKey(User)
    choice = models.ForeignKey(SlotChoice)

这很简单,但与您的要求略有不同。 您可以通过调整SlotChoice模型的“ str ”方法来使其更加有用,如上所示。

但是,如果您想真正按照原始问题来完成这项工作,则难度会稍大一些。 为了使这样的事情真正顺利进行,您将需要使用JavaScript:您的表单在加载时不知道您选择了哪个插槽,因此在更改插槽下拉列表时需要更改选择下拉列表。 一种简洁的方法是django-smart-selects模块。 这很容易使用-对于初学者-神奇地添加了JS。 然后您的模型将如下所示:

 from smart_selects.db_fields import ChainedForeignKey
    class Choice(models.Model):
        choice = models.CharField(max_length=300)

        def __str__(self):
            return self.choice

class User(models.Model):
    username=models.CharField(max_length=300)

class Slot(models.Model):
    slotname=models.CharField(max_length=300)


class SlotChoice(models.Model):
    slot=models.ForeignKey(Slot)
    choices = models.ManytoManyFields(Choice, related_name="adminchoices_related")

class UserChoice(models.Model):
    user = models.ForeignKey(User)
    slot = models.ForeignKey(Slot)

    choice = = ChainedForeignKey(
    SlotChoice,
    chained_field="slot",
    chained_model_field="slot",
    show_all=False,
    auto_choose=True,
    sort=True)

暂无
暂无

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

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