模型中的Django关系

2024-05-02 11:28:19 发布

您现在位置:Python中文网/ 问答频道 /正文

在Django中有名为ForeignKey和OneToMany/OneToOne的字段类型,我想知道在这个场景中我是使用ForeignKey还是关系类型作为字段类型?用户配置文件已被确定为OneToOne,但我不确定其他人。你知道吗

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE)
    fullname = models.CharField(max_length=100)
    dob = models.DateField()
    address = models.TextField()
    city = models.CharField(max_length=100)
    profilephoto = models.ImageField(default='default_profile.jpg', upload_to='reviewApp/static/profile_images')

class Product(models.Model):
    name = models.CharField(max_length=100)
    brand = models.CharField(max_length=100)
    cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)
    category = models.CharField(max_length=100)
    releasedate = models.DateField()
    description = models.TextField()
    productphoto = models.ImageField(default='default_product.jpg', upload_to='reviewApp/static/product_images')

class Review(models.Model):
    product = models.ForeignKey(Product)
    profile = models.ForeignKey(Profile)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    rating = model.PositiveSmallIntegerField(default=1, validators = [MinValueValidator(1), MaxValueValidator(5)])
    reviewtext = models.TextField()
    postdate = models.DateTimeField(auto_now_add=True)
    lastmodified = models.DateTimeField(auto_now=True)

ERD for Project


Tags: default类型modelmodelsproductprofilelengthmax
1条回答
网友
1楼 · 发布于 2024-05-02 11:28:19

因此,从我这里看到的情况来看,如果以下是你想要的,那就好了:

  • 用户只能有一个配置文件,并且一个配置文件仅与一个用户相关。你知道吗
  • 一个配置文件可以进行多次审阅,但审阅只属于一个配置文件。你知道吗
  • 一个产品可以有多个评审,但评审是针对一个产品的。你知道吗

根据删除后要保留在数据库中的内容,请小心为外键定义on\u delete参数。你知道吗

来自文档的更多信息:https://docs.djangoproject.com/fr/2.2/ref/models/fields/#arguments

相关问题 更多 >