三行代码  ›  专栏  ›  技术社区  ›  basskiller

如何使用左连接orm?

  •  1
  • basskiller  · 技术社区  · 4 天前

    class Ad_company(models.Model):
        idx = models.AutoField(primary_key=True)
        subject = models.CharField(max_length=255)
        memo = models.CharField(max_length=255)
        content = models.TextField()
        is_display = models.CharField(max_length=1)
        writer = models.CharField(max_length=255)
        write_date = models.DateTimeField()
        update_date = models.DateTimeField()
        delete_date = models.DateTimeField()
        deadline_date = models.DateTimeField()
        reply = models.IntegerField(blank=True)
        hits = models.IntegerField(blank=True)
        ad_apply = models.IntegerField(blank=True)
        ad_category1 = models.CharField(max_length=255)
        ad_category2 = models.CharField(max_length=255)
        ad_place = models.CharField(max_length=255)
        ad_age = models.CharField(max_length=255)
        ad_sex = models.CharField(max_length=255)
        ad_budget = models.BigIntegerField()
        ad_length = models.CharField(max_length=255)
        is_done = models.CharField(max_length=1)
        is_pay = models.CharField(max_length=1)
        ad_service = models.CharField(max_length=255)
        ad_object = models.CharField(max_length=255)
        is_file = models.CharField(max_length=1)
        ad_require = models.CharField(max_length=255)
    
        class Meta:
            managed = False
            db_table = 'ad_write_company'
    
    
    class Ad_company_apply(models.Model):
        idx = models.AutoField(primary_key=True)
        parent_idx = models.IntegerField()
        username = models.CharField(max_length=255)
        content = models.TextField()
        date = models.DateTimeField(default=datetime.now, blank=True)
        budget = models.BigIntegerField()
        term = models.IntegerField()
        is_done = models.CharField(max_length=1)
    
    
    SELECT * FROM ad_write_company INNER JOIN ad_write_company_apply ON ad_write_company.idx = ad_write_company_apply.parent_idx where ad_write_company_apply.is_done = 1 and ad_write_company_apply.username = 'asdffdsa'
    

    这是我的问题。但是我不能用orm进行连接查询。

    我的问题对吗?

    或者你们还有别的好主意吗?

    1 回复  |  直到 4 天前
        1
  •  1
  •   Willem Van Onsem    4 天前

    我建议你和一个年轻人一起工作 ForeignKey 从…起 Ad_company_apply Ad_company

    因此,重写 广告公司申请 模型至:

    class Ad_company_apply(models.Model):
        # …
        parent_idx = models.ForeignKey(
            Ad_company,
            db_column='parent_idx',
            on_delete=models.CASCADE
        )
        # …

    .filter(…) [Django-doc] 与:

    Ad_Company.objects.filter(ad_company_appy__isdone=1, ad_company_appy__username='asdffdsa')

    :Django中的模型是用 帕斯卡命名法 , 阿杜公司 AdCompany