Django model's OneToOne relationship - AttributeError: object has no attribute

Django model's OneToOne relationship - AttributeError: object has no attribute

请帮忙!

我正在构建一个简单的维护票务系统。

model Ticket 捕获初始数据。

model UpdateTicket 使响应者能够更新 Ticket 上的详细信息,并包括额外的评论字段和时间戳。 UpdatedTicketTicket 具有一对一关系,但我得到一个 AttributeError: 'Ticket' object has no attribute 当我尝试访问相关数据时。我已经通过管理站点向此 table 输入了一些数据,并且那里的关系工作正常。

这是模型

from django.db import models
from django.utils import timezone
from django.urls import reverse
from members.models import Member

class Ticket(models.Model):
    """ model to represent maintenance issue ticket """
    # id = models
    reporter = models.ForeignKey(Member, on_delete=models.CASCADE, null=True, related_name='+', db_column='reporter')
    location = models.ForeignKey(Member, on_delete=models.PROTECT, null=True, related_name='+', db_column='location')
    date_reported = models.DateTimeField(default=timezone.now)
    description = models.TextField(max_length=100)
    contractor = models.ForeignKey('Contractor', on_delete=models.PROTECT, null=True)

    class Meta:
        ordering = ['date_reported']
        permissions = [
            ("can_message", "add a new message"),
            ("can_update", "update a ticket"),
        ]


    def __str__(self):
        """ string to return the model name as text"""
        return f'{self.reporter}, {self.date_reported} GOTO -> '

    def get_absolute_url(self):
        """Returns the url to access a particular ticket instance."""
        return reverse('maintenance-ticket', args=[str(self.id)])


class UpdatedTicket(models.Model):
    ticket = models.OneToOneField(Ticket, on_delete=models.CASCADE, related_name='_ticket', primary_key=True,)
    comment = models.TextField(max_length=300, null=True)
    date_updated = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ['date_updated']

    def __str__(self):
        return f'referencing the OneToOneField'

这是我一直在尝试解决的错误(已编辑)

>>> from maintenance.models import Ticket
>>> t = Ticket.objects.filter(id=9).first()

>>> t.updatedticket
AttributeError: 'Ticket' object has no attribute 'updatedticket'

>>> t.ticket
AttributeError: 'Ticket' object has no attribute 'ticket'

>>> t._ticket
KeyError: '_ticket'
sqlite3.OperationalError: no such column: maintenance_updatedticket.ticket_id

The above exception was the direct cause of the following exception:
django.db.utils.OperationalError: no such column: maintenance_updatedticket.ticket_id

然后,只是为了测试 UpdatedTicket 中的数据是否存在 table;

>>> from maintenance.models import UpdatedTicket
>>> UpdatedTicket.objects.all()
sqlite3.OperationalError: no such column: maintenance_updatedticket.ticket_id
django.db.utils.OperationalError: no such column: maintenance_updatedticket.ticket_id

我认为在 table 中引用具有 OneToOne 关系的字段将是一件简单的事情。如果能理解我哪里出错了,将不胜感激。

这是迁移

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Ticket',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('date_reported', models.DateTimeField(default=django.utils.timezone.now)),
                ('description', models.TextField(max_length=100))
                ('contractor', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='maintenance.contractor')),
                ('location', models.ForeignKey(db_column='location', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='+', to=settings.AUTH_USER_MODEL)),
                ('reporter', models.ForeignKey(db_column='reporter', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ['date_reported'],
                'permissions': [('can_eat_scones', 'eat scones'), ('can_message', 'add a new message'), ('can_update', 'update a ticket')],
            },
        ),
        migrations.CreateModel(
            name='UpdatedTicket',
            fields=[
                ('ticket', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='_ticket', serialize=False, to='maintenance.ticket')),
                ('comment', models.TextField(max_length=300, null=True)),
                ('date_updated', models.DateTimeField(default=django.utils.timezone.now)),
            ],
            options={
                'ordering': ['date_updated'],
            },
        ),
    ]

提前致谢。

我认为这是由于在两个表的开发过程中创建的模型 ID 不匹配造成的。通过从 dbshel​​l 中删除 sqlite 数据库中的所有迁移和相关表并重新开始,它已经得到修复。