我正在尝试使用Django的过滤器和select_related过滤值。我能够获得基本项目,但我无法获得任何连接的字段。
item = Items.objects.filter(tests__company_user_id__user_id=user_id).filter(item_id=item_id).select_related("tests__company_user").values()
我的目标是将与项目相关联的用户的数据导入到项目返回中。这可能吗?
数据模型如下所示:
class Items(models.Model):
item_id = models.CharField(primary_key=True,max_length=100)
mailed_date = models.DateTimeField()
received_date = models.DateTimeField()
last_viewed = models.DateTimeField()
dateitemsent = models.DateTimeField()
itemsent = models.CharField(max_length=25)
itemret = models.CharField(max_length=25)
dateitemret = models.DateTimeField()
status = models.CharField(max_length=25)
class Tests(models.Model):
tests_id = models.CharField(primary_key=True, unique=True, max_length=100)
teststypetest_id = models.ForeignKey(TestsType)
dateitemord = models.DateTimeField()
testdate = models.DateTimeField()
teststypetest_id = models.ForeignKey(TestsType)
dateitemord = models.DateTimeField()
testdate = models.DateTimeField()
status = models.CharField(max_length=100)
item_id = models.ForeignKey(Kits)
company_user_id = models.ForeignKey(CompanyUser)
class CompanyUser(models.Model):
user_id = models.CharField(primary_key=True,max_length=100)
username = models.CharField(max_length=254,default="empty")
sec_question_1 = models.CharField(max_length=254)
sec_answer_1 = models.CharField(max_length=254)
sec_question_2 = models.CharField(max_length=254)
sec_answer_2 = models.CharField(max_length=254)
sec_question_3 = models.CharField(max_length=254)
sec_answer_3 = models.CharField(max_length=254)
答案 0 :(得分:0)
当您使用select_related()缓存已加入的对象信息但未检索时,您需要明确提取数据:
item = Items.objects.filter(tests__company_user_id__user_id=user_id).filter(item_id=item_id).select_related("tests__company_user").values("tests__company_user_id__sec_question_1", "tests__company_user_id__sec_question_2", ...)
修改强>
假设您只想要CompanyUser
中的两个字段:sec_question_1
和sec_question_2
:
from django.db.models import F
item = Items.objects.filter(tests__company_user_id__user_id=user_id).filter(item_id=item_id).select_related("tests__company_user").values().annotate(q1=F('tests__company_user_id__sec_question_1'), q2=F('tests__company_user_id__sec_question_2'))