【问题标题】:How to join not relational model in django rest framework?如何在 django rest 框架中加入非关系模型?
【发布时间】:2017-10-17 09:18:00
【问题描述】:

我有一个关于在 django rest 框架中加入而不是关系模型的问题。例如,我有两个模型:

  1. 模型类别模板

    class CategoryTemplate(models.Model):
         name = models.CharField(max_length=256)
    
  2. 模型商品

    class Commodity(models.Model):
         name = models.CharField(max_length=255, default=None, null=False)
    

    示例数据:

    *category template
    id    | name
     1    | Pupuk
     2    | Pestisida
    
    *commodity
    id    | name
     1    | Pisang
     2    | Semangka
    

我的问题是,该模型如何加入该模型以获得这样的结果?

 cat_temp_id | cat_temp_name | comm_id | comm_name | category
           1 |   Pupuk       |    1    | Pisang    | Pupuk Pisang
           1 |   Pupuk       |    2    | Semangka  | Pupuk Semangka
           2 |   Pestisida   |    1    | Pisang    | Pestisida Pisang
           2 |   Pestisida   |    2    | Semangka  | Pestisida Semangka

请指教。谢谢。

【问题讨论】:

    标签: python django django-models django-rest-framework


    【解决方案1】:

    您正在寻找的是笛卡尔积,而不是加入

    为此,如果您可以迭代模型,则无需弄乱模型。简单地写一个嵌套循环

    category_templates = CategoryTemplate.objects.all()
    commodities = Commodity.objects.all()
    
    for cat in category_templates:
        for comm in commodities:
            category = "%s %s" % (cat.name, comm.name)
    

    或使用itertools.product

    for (cat, comm) in itertools.product(
        CategoryTemplate.objects.all(),
        Commodity.objects.all()
    ):
        category = "%s %s" % (cat.name, comm.name)
    

    【讨论】:

      【解决方案2】:

      如果您指的是非关系型数据库,则无需像在关系型数据库中那样通过连接来获得最终结果。

      您想通过连接两个表来实现什么目标?

      【讨论】:

        猜你喜欢
        • 2018-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-07
        • 2012-11-16
        • 2013-12-22
        • 2015-04-12
        • 2016-05-30
        相关资源
        最近更新 更多