【问题标题】:how to bind two models in django如何在django中绑定两个模型
【发布时间】:2020-12-31 14:12:55
【问题描述】:

请帮助初学者。我正在尝试在 Django 中构建一个投票应用程序,我想更改我的管理面板,以便我可以在同一页面中更改和添加问题和选择 iv 已经尝试创建一个新模型并将问题和选择模型绑定在一起但是没用,请帮帮我。 这是我的投票应用程序中的 models.py,我遇到的另一个问题是我想为不同的问题提供不同数量的选择,但我不知道如何编写

from django.db import models

# Create your models here.
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
class Bind(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')    
    add_question =Question(question_text=question_text,pub_date=pub_date)

    choice_text_1= models.CharField(max_length=200,default='yes')
    votes_1= models.IntegerField(default=0)
    choice_text_2= models.CharField(max_length=200,default='yes')
    votes_2= models.IntegerField(default=0)
    choice_text_3= models.CharField(max_length=200,default='yes')
    votes_3= models.IntegerField(default=0)
    choice_text_4= models.CharField(max_length=200,default='yes')
    votes_4= models.IntegerField(default=0)
    add_choice1=Choice(choice_text=choice_text_1,votes=votes_1)
    add_choice2=Choice(choice_text=choice_text_2,votes=votes_2)
    add_choice3=Choice(choice_text=choice_text_3,votes=votes_3)
    add_choice4=Choice(choice_text=choice_text_4,votes=votes_4)
    def __str__(self):

        return self.question_text 
        return self.choice_text

这是我的管理面板 ID,我想更改它,我可以添加具有不同数量选择的问题,当我保存时,我可以在问题模型面板中找到保存问题,并在选择模型面板中找到选项,请帮助我初学者 enter image description here

这是views.py文件:

class IndexView(generic.ListView):
  template_name = 'polls/index.html'
  context_object_name = 'latest_question_list'
  def get_queryset(self):
    return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
  model = Question
  template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
  model = Question
  template_name = 'polls/results.html'
def vote(request, question_id):
 question = get_object_or_404(Question, pk=question_id)
 try:
  selected_choice = question.choice_set.get(pk=request.POST['choice'])
 except (KeyError, Choice.DoesNotExist):

  return render(request, 'polls/detail.html', {'question': question,'error_message': "You didn't select a choice.",})
 else:
  selected_choice.votes += 1
  selected_choice.save()

  return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

以及执行 python manage.py migrate 的错误

C:\projects\AM\FM\mysite>python manage.py migrate 操作到 perform:应用所有迁移:admin、auth、contenttypes、polls、 会话运行迁移:应用 polls.0009_auto_20200914_1002...回溯(最近一次通话最后一次):
文件 "C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init_.py", 第 1774 行,在 get_prep_value 中 return int(value) ValueError: int() 以 10 为底的无效文字:'choice'

上述异常是以下异常的直接原因:

Traceback(最近一次调用最后一次):文件“manage.py”,第 22 行,在 main() 文件“manage.py”,第 18 行,在 main execute_from_command_line(sys.argv) 文件 "C:\projects\AM\FM\lib\site-packages\django\core\management_init_.py", 第 401 行,在 execute_from_command_line utility.execute() 文件 "C:\projects\AM\FM\lib\site-packages\django\core\management_init_.py", 第 395 行,执行中 self.fetch_command(subcommand).run_from_argv(self.argv) 文件 "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py", 第 330 行,在 run_from_argv self.execute(*args, **cmd_options) 文件 "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py", 第 371 行,执行中 输出 = self.handle(*args, **options) 文件 "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py", 第 85 行,包裹 res = handle_func(*args, **kwargs) 文件 "C:\projects\AM\FM\lib\site-packages\django\core\management\commands\migrate.py", 第 243 行,在句柄中 post_migrate_state = executor.migrate( 文件 "C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py", 第 117 行,在迁移中 state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) 文件 "C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py", 第 147 行,在 _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) 文件 "C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py", 第 227 行,在 apply_migration state = migration.apply(state, schema_editor) 文件 "C:\projects\AM\FM\lib\site-packages\django\db\migrations\migration.py", 第 124 行,申请中 operation.database_forwards(self.app_label, schema_editor, old_state, project_state) 文件 "C:\projects\AM\FM\lib\site-packages\django\db\migrations\operations\fields.py", 第 104 行,在 database_forwards 中 schema_editor.add_field(文件“C:\projects\AM\FM\lib\site-packages\django\db\backends\sqlite3\schema.py”, 第 328 行,在 add_field self.remake_table(model, create_field=field) 文件 "C:\projects\AM\FM\lib\site-packages\django\db\backends\sqlite3\schema.py", 第 189 行,在 remake_table 中 self.effective_default(create_field) 文件 "C:\projects\AM\FM\lib\site-packages\django\db\backends\base\schema.py", 第 303 行,在有效默认值中 返回 field.get_db_prep_save(self.effective_default(field), self.connection) 文件 "C:\projects\AM\FM\lib\site-packages\django\db\models\fields\related.py", 第 971 行,在 get_db_prep_save 中 返回 self.target_field.get_db_prep_save(value, connection=connection) 文件 "C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init.py", 第 823 行,在 get_db_prep_save 中 返回 self.get_db_prep_value(value, connection=connection,prepared=False) 文件 "C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init.py", 第 2388 行,在 get_db_prep_value value = self.get_prep_value(value) 文件 "C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init.py", 第 1776 行,在 get_prep_value 中 raise e.class( ValueError: Field 'id' expected a number but got 'choice'.

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    您不能直接将其他模型分配给其他模型的字段。您必须使用ForeignKey(一个对象到多个可引用对象)或ManyToManyField(许多对象可以包含到此对象)。

    此时,您可能需要考虑将 class Bind 设置为 class Questionnaire,因为您正在合并它们。

    这样,应用了修复和冗余,这应该是最终代码(仅用于继承!)

    
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        question_choices = models.ForeignKey("Choice", on_delete=models.CASCADE)
        pub_date = models.DateTimeField(help_text='date published', auto_now_add=True)
        def __str__(self):
            return self.question_text
    
    # No need to refer to the `Question` Model unless you have something to do important.
    # Cross-Reference is okay, but its redundant unless special handling is required (for instance, you want pure integrity of ownership of this object, etc. But its quite hard to manage if your models were scaling.)
    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
    
    class Questionnaire(models.Model):
        questions = models.ManyToManyField("Question", blank=True)
        pub_date = models.DateTimeField(help_text='date published', auto_now_add=True)    
    
        def __str__(self):
            return self.question_text 
    

    注意事项:

    1. 如果您仔细阅读更改,您可能会看到自己,为什么我以“str”形式分配对象?那是因为 Django 能够加载对象,甚至是在需要它的对象之后。意思是,您不需要在顶部放置另一个对象来引用,而是只需将它放在 str 引用中,即使该对象被放置在任何地方,您也可以使用。

    2. 请注意,在DateTimeField 中,您可能需要考虑auto_now_add=True,它会自动处理首次保存此对象的时间。

    3. 我想在问题下做出所有选择。这很好,因为如果您想提出问题,有一个字段可供您选择。

    4. 为了清楚起见,我将Bind 更改为Questionnaire。这应该足以查看与您的模型的关系或继承。

    5. 我使用ManyToManyField 将问题(或对象)的数量设置为此Questionnaire

    【讨论】:

    • 非常感谢您的帮助 h 不知道为什么,但我收到此错误 ValueError: Field 'id' expected a number but got 'choice'。这是因为 views.py 吗?
    • 我不确定,我想在你的问题中提供一个追溯,以便我们可以弄清楚更多。
    • 嘿,您的views.py 中有一个错误,即此查询selected_choice = question.choice_set.get(pk=request.POST['choice'])。我不确定request.POST 的值是多少,但我保证它不是引发错误的问题的关键。
    • 非常感谢您的时间和关注,但我无法处理此错误我删除了 Questioner 类但我不断收到此错误我不知道该怎么办请帮助我。
    • 非常感谢它的工作。再次感谢您的时间和关注
    【解决方案2】:

    通常,在这种情况下,您不需要创建“绑定”模型。您只需将“序列”整数字段添加到您的选择模型中。那么,每个问题可以有无限多的选择,例如:

    Choice.objects.create(question=question1, sequence=0)
    Choice.objects.create(question=question1, sequence=1)
    Choice.objects.create(question=question1, sequence=2)...
    

    【讨论】:

    • 非常感谢您的时间和关注。你能帮我解决我在执行 python manage.py migrate 时遇到的这个新问题吗? ValueError: Field 'id' expected a number but got 'choice'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 2021-10-01
    相关资源
    最近更新 更多