嗨,我需要一个非常非常简单的例子。首先是我的模特:
#This my student models
from django.db import models
SEX_CHOICES= (
('M', 'Male'),
('F', 'Female'),
)
class Students(models.Model):
student_name = models.CharField(max_length=50)
student_sex = models.CharField(max_length=8, choices=SEX_CHOICES)
student_city = models.Charfield(max_length=50)
student_bio = models.TextField()
def __unicode__(self):
return self.student_name
O.K。让我们看看我的班级模型。
#This my Classes models
from django.db import models
from myproject.students.models import *
class Classes(models.Model):
class_number= models.CharField(max_length=50)
class_student_cities = models.ForeignKey(Students)
class_year = models.DateField()
def __unicode__(self):
return self.class_number
我的classes / admin.py文件看起来像这样:
from myproject.classes.models import *
from myproject.students.models import *
from django.contrib import admin
class ClassesChoiceField(Students):
class_student_cities = Classes.objects.get(id=1).class_student_cities.student_city
admin.site.register(Classes)
我收到此错误:
DoesNotExist at /admin/classes/classes/add/
Classes matching query does not exist.
如何在 class_student_city 区域中显示 Students.student_city 数据? 我猜这是关于django-admin区域的。 当我使用 ForeignKey(学生)时,我只是在该区域看到 Students.student_name 数据:S。我真的想知道我该怎么做?你能举个例子吗? 非常感谢!
答案 0 :(得分:1)
答案 1 :(得分:0)
要从queryset获取student_city,您可以使用:
Classes.objects.get(id=1).class_student_cities.student_city
如果你想将你的foreignkey字段与主键相关联,你应该使用to_field
参数
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.to_field
就像:
class_student_cities = models.ForeignKey(Students, to_field='student_city')
答案 2 :(得分:0)
有一些问题 - 基本上事情'不太正确',这就是为什么你不断被引用到文档。
以下是admin.py的示例:
from django.contrib import admin
from articles.models import Article
def show_articletype_thumbnail(self):
return self.image.admin_thumbnail()
show_articletype_thumbnail.allow_tags=True
show_articletype_thumbnail.short_description = 'Image'
class ArticleAdmin(admin.ModelAdmin):
save_on_top = True
list_display = ['status', 'articletype', 'issue', 'penname', 'issue', show_articletype_thumbnail]
list_display_links = ['articletype']
list_filter = ['articletype', 'allow_comments', 'template', 'issue']
admin.site.register(Article, ArticleAdmin)