gpt4 book ai didi

python - 向后关系如何与 Django 查询集配合使用

转载 作者:行者123 更新时间:2023-11-29 10:36:25 25 4
gpt4 key购买 nike

我有以下 models.py:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.


class IndustryCat1(models.Model):
name = models.CharField(max_length=256)

class Meta:
managed = False
db_table = 'industry_cat_1'



class IndustryCat2(models.Model):
name = models.CharField(max_length=256)
num = models.CharField(max_length=10)
label = models.CharField(max_length=200)
industry_cat_1_id = models.ForeignKey('IndustryCat1')

class Meta:
managed = False
db_table = 'industry_cat_2'



class IndustryCat3(models.Model):
name = models.CharField(max_length=256)
num = models.CharField(max_length=10)
label = models.CharField(max_length=200)
industry_cat_2_id = models.ForeignKey('IndustryCat2', blank=True, null=True, related_name='industry_cat_2_id')

class Meta:
managed = False
db_table = 'Industry_cat_3'




class IndustryCat4(models.Model):
name = models.CharField(max_length=256)
num = models.CharField(max_length=10)
label = models.CharField(max_length=200)
industry_cat_3_id = models.ForeignKey('IndustryCat3', blank=True, null=True, related_name='industry_cat_3_id')

class Meta:
managed = False
db_table = 'Industry_cat_4'

这是我正在编写查询的文件:Industries.py:

from demo.models import IndustryCat1, IndustryCat2
import datetime
from django.db.models import Q

class Industries:


@staticmethod
def getIndustries(indId):
try:

b = IndustryCat1.objects.filter()
return b.industrycat2_set.all() # Returns all Entry objects related to Blog.

except IndustryCat1.DoesNotExist:
return None

这是我需要获取在 Industries.py 中实现的查询返回结果的文件: View .py:

# -*- coding: utf-8 -*-
from django.http import HttpResponse
from models import IndustryCat1
from demo.core.persistence.Industries import *
from django.shortcuts import get_object_or_404, render, render_to_response
from django.core import serializers
import json

def index(request):

industry = Industries()

qs = industry.getIndustries(1)

return HttpResponse(serializers.serialize("json", qs))

context = {'indus': indus}

return render(request, 'demo/test/industries_catagories.html', context)

我的表结构如下:

IndustryCat1 有两列 id 和 name 的结果。

IndustryCat2 将 IndustryCat1 id 作为外键。

我想获取所有 IndustryCat1 记录及其对应的 IndustryCat2

我试图在 Industries.py 中使用以下查询来执行此操作:

 b = IndustryCat1.objects.filter()
return b.industryCat2_set.all()

但我收到以下错误:

AttributeError at /demo/ 'QuerySet' object has no attribute 'industryCat2_set'

任何有关如何应用此类查询的帮助都会对我有所帮助,因为我陷入困境。

提前致谢。

最佳答案

默认相关名称应全部小写。

...
b.industrycat2_set.all() # correct syntax but incorrect usage

OTOH,您有一个查询集而不是单个对象。您无法直接从查询集中访问反向外键关系,只能从 filter 返回的查询集中的每个对象访问。

最后一点,请勿将 _id 添加到外键的字段名称中。当您实际需要访问外键字段的 id 时,一切都会变得困惑。

关于python - 向后关系如何与 Django 查询集配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46340992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com