如何正确显示Author
名称?
the experimental Elasticsearch integration
它只在那里显示'破折号'。
以下是我的代码。
@admin.register(Solution)
class SolutionAdmin(admin.ModelAdmin):
def get_original_question(self, obj):
se = obj.question_code
return format_html(se.question)
def get_name(self, obj):
se = obj.user_id.name
return se
fieldsets = [
('question', {'fields': ['get_original_question']}),
('author', {'fields': ['get_name']}),
('solution', {'fields': ['body']}),
]
readonly_fields = ('get_original_question','get_name')
get_original_question.short_description = 'question'
get_name.short_description = 'author'
class Question(models.Model):
question = RichTextField(blank=True, null=True)
question_code = models.CharField(max_length=15,unique=True)
class Solution(models.Model):
question_code = models.OneToOneField(Question, to_field='question_code', db_column='question_code')
user_id = models.ForeignKey('Users',to_field='id' ,db_column='ID')
body = RichTextField(blank=True, null=True)
class Users(models.Model):
id = models.AutoField(db_column='ID', primary_key=True)
name = models.CharField(db_column='Name', max_length=255, blank=True, null=True)
>>> Solution.objects.get(pk=1490).user_id
Traceback (most recent call last):
File "/home/aaron/.virtualenvs/django/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 178, in __get__
rel_obj = getattr(instance, self.cache_name)
AttributeError: 'Solution' object has no attribute '_user_id_cache'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/aaron/.virtualenvs/django/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 184, in __get__
rel_obj = self.get_object(instance)
File "/home/aaron/.virtualenvs/django/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 159, in get_object
return qs.get(self.field.get_reverse_related_filter(instance))
File "/home/aaron/.virtualenvs/django/lib/python3.5/site-packages/django/db/models/query.py", line 379, in get
self.model._meta.object_name
den.models.DoesNotExist: Users matching query does not exist.
更新:
>>> Solution.objects.get(pk=180).user_id
<Users: John>
>>> Solution.objects.get(pk=180).user_id.name
'John'
>>> Solution.objects.get(pk=1490).user_id.name
Traceback (most recent call last):
File "/home/aaron/.virtualenvs/django/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 178, in __get__
rel_obj = getattr(instance, self.cache_name)
AttributeError: 'Solution' object has no attribute '_user_id_cache'
答案 0 :(得分:1)
在解决方案模型中
class Solution(models.Model):
question_code = models.OneToOneField(Question, to_field='question_code', db_column='question_code')
user_id = models.ForeignKey('Users',to_field='id' ,db_column='ID')
body = RichTextField(blank=True, null=True)
user_id
字段,我指向错误的列,因此将db_column更改为user_id
user_id = models.ForeignKey('Users',to_field='id' ,db_column='user_id')
解决问题。