【问题标题】:Django many-to-many relationship with extra fieldsDjango 与额外字段的多对多关系
【发布时间】:2011-08-15 00:34:22
【问题描述】:

我正在使用 django-admin 构建一个简单的生物数据库接口来填充数据库。我想对鱼类物种的问卷使用多对多关系(一份问卷可以有多个物种,一个物种可以出现在多个问卷中)。有问题的两个模型:

class Species(models.Model):
    fish_spp_name = models.CharField(max_length=255, unique=True)


class Questionaire(models.Model):
    # ...
    fish_caught = models.ManyToManyField(Species)

现在,我希望我的数据包含每个调查问卷中捕获的每个物种的数量。因此,例如,我可以将 3 个不同的物种与问卷 id=1 相关联,但我如何包括第一个物种的 2 个、第二个物种的 1 个和第三个物种的 4 个?

【问题讨论】:

标签: django many-to-many


【解决方案1】:

【讨论】:

    【解决方案2】:

    定义另一个模型Caught 来保存每次捕获的信息。给它一个related_name 使它更容易在你的代码中引用。您可能还想unique_together 适当的字段。

    class Species(models.Model):
        name = models.CharField(max_length=255, unique=True)
    
        def __unicode__(self):
            return '%s/%d' % self.name
    
    class Questionaire(models.Model):
        pass
    
    class Caught(models.Model):
        species = models.ForeignKey(Species)
        number = models.IntegerField()
        questionaire = models.ForeignKey(
            Questionaire, related_name='catches')
    
        def __unicode__(self):
            return '%s/%d' % (self.species.name, self.number)
    

    像这样使用它:

    (InteractiveConsole)
    >>> from app.models import *
    >>> s1 = Species(name='Salmon')
    >>> s1.save()
    >>> s2 = Species(name='Mackerel')
    >>> s2.save()
    >>> q = Questionaire()
    >>> q.save()
    >>> c1 = Caught(species=s1, number=7, questionaire=q)
    >>> c2 = Caught(species=s2, number=5, questionaire=q)
    >>> c1.save()
    >>> c2.save()
    >>> q.catches.all()
    [<Caught: Salmon/7>, <Caught: Mackerel/5>]
    >>>
    

    【讨论】:

    • 好的,所以实际上我只是使用外键而不是多对多来定义我的模型?这很好,尽管我最终得到了两种用于数据输入的表格(问卷调查,然后是钓到的鱼)。之前,我使用了从问卷到物种的多对多,它为鱼类物种产生了一个方便的多项选择。我只是想知道是否有可能在问卷表格中扩展这一点,以便所有这些数据都可以记录在一个表格中(即选择产生另一种表格用于输入捕获号码的物种?无论哪种方式你的方式肯定有效。
    • 好的,知道了。如果我为 Caught model.Admin 指定一个内联类,并将其作为内联在 Questionnaire model.Admin 中引用,我会得到我正在寻找的行为:)
    • 这个答案不再有效,因为 Django 支持“开箱即用”的多对多对象。 OP 考虑更改接受的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 2017-11-22
    • 1970-01-01
    相关资源
    最近更新 更多