简体   繁体   English

Django - DRF 多对多和外键

[英]Django - DRF ManyToMany and ForeignKey

I am building an api for entertainment management.我正在建设一个娱乐管理的api。

The user can create empty project or projects with show, tour and festival.用户可以创建空项目或带有表演、旅游和节日的项目。 User can also create show and specify project id.用户还可以创建节目并指定项目 ID。

A project can contain:一个项目可以包含:

  1. Show 0 to *显示 0 到 *
  2. Tour 0 to *游览 0 至 *
  3. Festival 0 to *节日 0 至 *

A Tour can contain:游览可以包含:

  1. Show 0 to 1显示 0 到 1

A Festival can contain:节日可以包含:

  1. Show 0 to *显示 0 到 *

A Show, Tour and Festival necessarily part of a Project.表演、旅游和节日必然是项目的一部分。

Here are my models:这是我的模型:

class Project(models.Model):
    """Models for Projects"""
    name = models.CharField(max_length=255, unique=True)
    shows = models.ManyToManyField('Show', blank=True)
    festivals = models.ManyToManyField('Festival', blank=True)
    tours = models.ManyToManyField('Tour', blank=True)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    date_created = models.DateTimeField(auto_now_add=True)
    last_update = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class Show(models.Model):
    """Models for Shows"""
    name = models.CharField(max_length=255, unique=True)
    start_date = models.DateTimeField(default=timezone.now, blank=True)
    end_date = models.DateTimeField(default=timezone.now, blank=True)
    tours = models.ManyToManyField('Tour', blank=True)
    festivals = models.ManyToManyField('Festival', blank=True)
    projects = models.ForeignKey(Project, on_delete=models.CASCADE, default=None)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    date_created = models.DateTimeField(auto_now_add=True)
    last_update = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class Tour(models.Model):
    """Models for Tour."""
    name = models.CharField(max_length=255, unique=True)
    start_date = models.DateTimeField(default=timezone.now, blank=True)
    end_date = models.DateTimeField(default=timezone.now, blank=True)
    production = models.CharField(max_length=255, blank=True)
    shows = models.ForeignKey(Show, on_delete=models.CASCADE, blank=True, null=True)
    projects = models.ForeignKey(Project, on_delete=models.CASCADE, default=None)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    date_created = models.DateTimeField(auto_now_add=True)
    last_update = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class Festival(models.Model):
    """Models for Festival."""
    name = models.CharField(max_length=255, unique=True)
    start_date = models.DateTimeField(default=timezone.now, blank=True)
    end_date = models.DateTimeField(default=timezone.now, blank=True)
    address_1 = models.CharField(max_length=128, blank=True)
    address_2 = models.CharField(max_length=128, blank=True)
    city = models.CharField(max_length=64, default="Paris")
    state = models.CharField(max_length=25, default='France')
    zip_code = models.CharField(max_length=8, default="92000")
    gps = models.CharField(max_length=255, blank=True)
    technical_rider = models.FileField(null=True, upload_to=riders_file_path)
    shows = models.ForeignKey(Show, on_delete=models.CASCADE, blank=True, null=True)
    projects = models.ForeignKey(Project, on_delete=models.CASCADE, default=None)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    date_created = models.DateTimeField(auto_now_add=True)
    last_update = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

everything works fine but I have a doubt about the double relationship m2m / foreignkey between:一切正常,但我对 m2m / foreignkey 之间的双重关系有疑问:

class Project(models.Model):
    """Models for Projects"""
    shows = models.ManyToManyField('Show', blank=True)

AND

class Show(models.Model):
    """Models for Shows"""
    projects = models.ForeignKey(Project, on_delete=models.CASCADE, default=None)

Your implementation is incorrect.您的实施不正确。 In Django when you specify relationships you only do so one one side of them.在 Django 中,当您指定关系时,您只能指定其中的一侧。 You seem confused about what type of relationships these models should have.您似乎对这些模型应该具有何种类型的关系感到困惑。

Can a project have multiple shows?一个项目可以有多场演出吗? It seems so.好像是的。 Can a show be part of multiple projects?一个节目可以是多个项目的一部分吗?

If the answer to the second question is yes then you should use a many-to-many relationship.如果第二个问题的答案是肯定的,那么您应该使用多对多关系。 If not, then this should be a one-to-many relationship.如果不是,那么这应该是一对多的关系。

M2M Example: Functionality-wise it doesn't matter where you place the ManyToManyField. M2M 示例:在功能方面,放置 ManyToManyField 的位置并不重要。 It creates a symmetric relationship.它创建了一个对称关系。 But you should put it in the Model where it makes the most 'sense'.但是你应该把它放在 Model 中它最“有意义”的地方。 That's the model from which you'll be able to access and update the relationship info from the Django admin这是 model,您可以从 Django 管理员那里访问和更新关系信息

# m2m example 
class Project(models.Model):
    shows = models.ManyToManyField(Show, related_name="projects")

class Show(models.Model):
    ...   

1toM Example: 1toM 示例:

# one-to-many example
class Project(models.Model):
    ...

class Show(models.Model):
    ...
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="shows")

These two implementations can't (and definitely shouldn't) be mixed up as they define different types of relationships.这两个实现不能(而且绝对不应该)混淆,因为它们定义了不同类型的关系。 If you struggle to understand the difference between them i recommend you to checkout this video (not the whole thing obviously).如果您很难理解它们之间的区别,我建议您查看此视频(显然不是全部)。 Once you have established which type of relationship you need, it's going to be a child's play to implement your Django models and to understand what you can do with them.一旦您确定了所需的关系类型,实现您的 Django 模型并了解您可以使用它们做什么将是小菜一碟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 多对多、外键关系模型中的 DRF 更新插入 - DRF Update Insert in ManytoMany, ForeignKey Relationship Models Django DRF 在序列化程序中获取外键值 - Django DRF get ForeignKey values in serializer django - 在ManyToMany和ForeignKey中使用related_name - django - using of related_name in ManyToMany and in ForeignKey Django(DRF):以不同方式序列化和反序列化ManyToMany字段? - Django (DRF): Serialize and deserialize a ManyToMany field differently? Django ForeignKey.limit_choices_to with ForeignKey to ManyToMany 场景 - Django ForeignKey.limit_choices_to with ForeignKey to ManyToMany scenario Django DRF外键序列化器-如何仅返回最新的object? - Django DRF foreignkey serializer - how to return only the latest object? Django针对ForeignKey并通过manytomany子查询的结果进行过滤 - Django filter against ForeignKey and by result of manytomany sub query 如何在Django中的许多关系中为每个外键创建一个表单字段 - How to create a form field for every foreignkey in manytomany relationship in django Django 创建一个models.ManyToMany和models.ForeignKey到同一个表 - Django create a models.ManyToMany and models.ForeignKey to the same table Django 中的 OneToOne、ManyToMany 和 ForeignKey 字段有什么区别? - Whats the difference between a OneToOne, ManyToMany, and a ForeignKey Field in Django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM