0

我试图理解 django 模型中的这种多字段逻辑。

我有两个 django 模型:locationimage.

我还有另一个名为location_has_image. 该模型以这种形式定义。

class location_has_image(models.Model):
  of_location = models.ForeignKey(location,related_name="of_location")
  of_image = models.ForeignKey(image,related_name="of_image")

我的问题是,当我保存新对象locationimage对象时,我是否必须将一些东西保存到这个模型中?还是会location_has_image自动将其设置为那些新创建的对象?还是我在这里想错了?

请帮忙!

4

1 回答 1

1

您应该改用ManyToManyField。它为您创建中间连接表并对其进行管理。

来自 Django 文档的示例:

from django.db import models

class Publication(models.Model):
    title = models.CharField(max_length=30)

    def __unicode__(self):
        return self.title

    class Meta:
        ordering = ('title',)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

    def __unicode__(self):
        return self.headline

    class Meta:
        ordering = ('headline',)

示例: https ://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/

现场文档: https ://docs.djangoproject.com/en/dev/ref/models/fields/#ref-manytomany

于 2013-03-28T03:07:28.903 回答