简体   繁体   English

如何在Django Rest框架中加入非关系模型?

[英]How to join not relational model in django rest framework?

i have a problem about join not relational model in django rest framework. 我在django rest框架中有关于不加入关系模型的问题。 for example, i have two model : 例如,我有两个模型:

  1. Model Category template 型号类别模板

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

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

    Example Data: 示例数据:

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

my question is, with that model how to join that model to get the result like this ? 我的问题是,使用该模型,如何加入该模型以得到这样的结果?

 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

Please advice. 请指教。 Thank you. 谢谢。

If you are referring to the non-relational database there is no need of join to achieve the final outcome as you do in the relational database. 如果您引用的是非关系数据库,则不需要像在关系数据库中那样进行联接以达到最终结果。

What is the goal you are trying to achieve by joining two tables? 通过连接两个表要达到的目标是什么?

What you are looking for is the cartesian product , not a join . 你所寻找的是笛卡尔乘积 ,而不是加入

For that there is no need to mess with the models if you can just iterate over them. 为此,如果您可以对模型进行迭代,则无需弄乱它们。 Simply write a nested loop 只需编写一个嵌套循环

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)

or use itertools.product 或使用itertools.product

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM