在Model Admin Django中编辑ForeignKey的所有实例的所有属性

时间:2016-07-07 17:47:26

标签: django django-models django-admin

构建应用程序以快速向外键添加数字。

所以我对Django很新,我已经在这里和Django的文档中查找了相关的问题。我发现的是内联AdminModel,但这不是我想要的。

from django.db import models
from django.utils.encoding import python_2_unicode_compatible
import datetime
from django.utils import timezone


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date= models.DateTimeField('date published')

    def __str__(self):
        return self.question_text


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete= models.CASCADE)
    choice_text = models.CharField(max_length = 200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text

我想要一个包含ForeignKey.So的所有实例的表格,例如,使用教程代码,应该可以编辑每个choice_text并同时投票到所有问题(这样就不必在两者之间跳转)添加内容的不同问题)。这可能吗? 在此先感谢您的帮助!

Here a mock-up of the project:

2 个答案:

答案 0 :(得分:0)

查看Django reference for the meta api 看看reference for model fields 这些的组合应该可以解决您的问题。 伪代码,

all_fields = MyModel._meta.fields
for field in all_fields:
    //Check if field is foreign key, field.get_internal_key() should work.
    //Find foreign key

答案 1 :(得分:0)

你的问题是你从错误的角度出发,这就是为什么你难以解释你想要实现的目标。您正尝试从Question模型开始,而您想要的是批量更新Choice(主要问题)并显示相关问题的文本(次要问题)。

您可以使用此list_editable批量修改Choice

class ChoiceAdmin(admin.ModelAdmin):
    list_display = ['__str__', 'question_text', 'choice_text', 'votes']
    list_editable = ['choice_text', 'votes']
    ordering = 'question'

    def question_text(self, obj):
        return obj.question.question_text
    question_text.short_description = "Question"
相关问题