简体   繁体   中英

How to join not relational model in django rest framework?

i have a problem about join not relational model in django rest framework. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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