Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
878 views
in Technique[技术] by (71.8m points)

python - error when query django database: ValueError: The annotation 'code' conflicts with a field on the model

I use Django2 and sqlite in windows 10 for a course management website.

when I tried to query the database in view.py using

query_results_3 = CourseInfo.objects.values('title', code=course_code[:5])

error occurs:

ValueError: The annotation 'code' conflicts with a field on the model.

model.py:

class CourseInfo(TimeStampedModel):  # school or center
code = models.CharField(max_length=20, unique=True, db_index=True)
title = models.CharField(max_length=200)
school = models.ForeignKey(School, on_delete=models.SET_NULL, blank=True, null=True)
postgraduate = models.BooleanField(default=False)  # indicate Postgraduate course
discipline = models.ForeignKey(Discipline, on_delete=models.SET_NULL, blank=True, null=True)  # should not be null
pattern = models.CharField(max_length=120, choices=PRESENTATION_PATTERN, blank=True, null=True,
                           help_text="Presentation Pattern")
type = models.CharField(max_length=2, choices=(('PT', 'Part-Time'), ('FT', 'Full-Time'), ('OL', 'Online')))
available = models.BooleanField(default=True)  # mean Active or Retired

semesters = models.ManyToManyField('Semester', through="Course")  # auto have semestercourse_set

def __str__(self):
    return "{} - {}".format(self.code, self.title)

class Meta:
    constraints = [models.UniqueConstraint(fields=['code', 'type'], condition=models.Q(available=True),
                                           name='unique_course_type')]
    ordering = ['code', ]

How to change my code to let the error disapear?

question from:https://stackoverflow.com/questions/65679853/error-when-query-django-database-valueerror-the-annotation-code-conflicts-wi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should do:

query_results_3 = CourseInfo.objects.filter(code=YOUR_CONDITION).values('title')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...