在 Django 中使用 ForeignKey 加入 2 个表
join 2 tables with ForeignKey in django
我有一张图片 table 由我所有的图片组成
我有一个产品 table
我想在我的产品中使用不止一张图片 table
这怎么可能 ?
我不想在图像中写 ForeignKey table 因为我想在其他地方使用我的图像
models.py
from django.db import models
class Image (models.Model):
path = models.CharField(max_length=200)
class Product (models.Model):
name = models.CharField(max_length=100)
price = models.FloatField(default=0)
description = models.TextField(max_length=10000)
image = models.ForeignKey(Image,on_delete=models.DO_NOTHING)
根据我的理解,您想在 Image
和 Product
之间建立 多对多 关系,那么您只需将其添加到 Product
class
from django.db import models
class Image (models.Model):
...
class Product (models.Model):
...
images = models.ManyToManyField(Image)
我有一张图片 table 由我所有的图片组成 我有一个产品 table 我想在我的产品中使用不止一张图片 table 这怎么可能 ? 我不想在图像中写 ForeignKey table 因为我想在其他地方使用我的图像
models.py
from django.db import models
class Image (models.Model):
path = models.CharField(max_length=200)
class Product (models.Model):
name = models.CharField(max_length=100)
price = models.FloatField(default=0)
description = models.TextField(max_length=10000)
image = models.ForeignKey(Image,on_delete=models.DO_NOTHING)
根据我的理解,您想在 Image
和 Product
之间建立 多对多 关系,那么您只需将其添加到 Product
class
from django.db import models
class Image (models.Model):
...
class Product (models.Model):
...
images = models.ManyToManyField(Image)