如何将同一对象添加到ManyToMany字段? [英] How can I add the same object to a ManyToMany field?

查看:52
本文介绍了如何将同一对象添加到ManyToMany字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关如何将同一对象(对一个对象的引用)保存到ManyToManyField中的帮助.例如,我有这样的模型:

I need help on how to save the same (reference to an) object into a ManyToManyField. For example I have models like this:

class Material(models.Model):
    name = models.CharField(max_length=50)

class Compound(models.Model):
    materials = models.ManyToManyField(Material)

在此示例中,化合物可以由一种或多种不同的材料制成,也可以由相同制成 Material 两次(在 Material 模型中,相同的 id ).

In this example, the Compound can be made of one or many different Materials, and it also could be made from the same Material twice (same id in Material model).

如果我尝试通过 ModelForm 保存,则第二个 Material 将被丢弃,因为它与第一个具有相同的 id 材质.

If I try to save through a ModelForm, the second Material is discarded because it has the same id as the first Material.

什么是最好的方法?

谢谢!

推荐答案

我建议按照我在这里做什么?好吧,Django通常会自动生成一个中间表,用于保存将化合物与元素相关联的密钥对.在这种情况下,我们将自己对其进行定义,不仅如此,我们还将为关系添加其他数据,即您所说的数量.

What am I doing here? Well, Django normally automatically generates an intermediary table for holding pairs of keys associating compounds to elements. In this case we're definiting it ourselves, but not only that, we're adding additional data to the relationship i.e. the quantity you speak of.

作为示例用法,您可以这样做:

As an example usage, what you might do is this:

$ python manage.py shell
from project.app.models import *

oxygen = Material(name="oxygen")
hydrogen = Material(name="hydrogen")
water = Compound(name="water")

oxygen.save()
hydrogen.save()
water.save()

water_chemistry_oxygen = CompoundMaterials(Material=oxygen, Compound=Water, Quantity=1)
water_chemistry_hydrogen = CompoundMaterials(Material=hydrogen, Compound=Water, Quantity=2)

water_chemistry_oxygen.save()
water_chemistry_hydrogen.save()

这篇关于如何将同一对象添加到ManyToMany字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆