簡體   English   中英

Django 查詢失敗,_id 未使用或創建或引用

[英]Django query fails with _id that is not used or created or referenced to

我以前使用過查詢集,雖然這是我第一次嘗試加入表,但到目前為止它還沒有工作。 我正在使用 django 3.2 和 python 3.8.1

我的模型.py

class Mainjoinbook(models.Model):
    fullsitename = models.TextField(primary_key=True)
    creationdate = models.DateTimeField()
    entrytypeid = models.BigIntegerField(blank=True, null=True)
    title = models.TextField(blank=True, null=True)
    tickettype = models.TextField(blank=True, null=True)
    ticket = models.TextField(blank=True, null=True)
    status = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'mainlogbook'

class Sitelocation(models.Model):
    site_name = models.TextField(primary_key=True)
    latitude = models.TextField(blank=True, null=True)
    longitude = models.TextField(blank=True, null=True)
    sites = models.ForeignKey(Mainjoinbook, on_delete=models.DO_NOTHING)

    class Meta:
        managed = False
        db_table = 'tblsiteaccess'

我試圖從我的views.py中加入的兩個表中獲取所有值

qrylocations = Sitelocation.objects.select_related('sites').filter(sites__status='OPEN')

這會導致此錯誤,因為該列是由 django 創建的,但不屬於該表。 我仍然無法解決這個問題,因為我嘗試了很多選項,但總是遇到某種錯誤,我希望有人能幫助我看看我在加入定義的主鍵上的表時做錯了什么

psycopg2.errors.UndefinedColumn: column tblsiteaccess.sites_id does not exist

SQL output 如下所示。

output 來自 qrylocations.query

SELECT "tblsiteaccess"."site_name", "tblsiteaccess"."latitude", "tblsiteaccess"."longitude", "tblsiteaccess"."sites_id", "mainlogbook"."fullsitename", "mainlogbook"."log_id", "mainlogbook"."creationdate", "mainlogbook"."entrytypeid", "mainlogbook"."title", "mainlogbook"."tickettype", "mainlogbook"."ticket", "mainlogbook"."status" FROM "tblsiteaccess" INNER JOIN "mainlogbook" ON ("tblsiteaccess"."sites_id" = "mainlogbook"."fullsitename") WHERE "mainlogbook"."status" = OPEN

ForeignKey自然需要數據庫表中的一列。 由於site_name本身是主鍵,因此您應該在此處將其用作ForeignKey ,事實上,這需要是OneToOneField [Django docs]而不是ForeignKey ,因為它也是主鍵並且需要是唯一的:

class Sitelocation(models.Model):
    site_name = models.OneToOneField(
        Mainjoinbook,
        on_delete=models.CASCADE,
        primary_key=True,
        db_column='site_name'
    )
    latitude = models.TextField(blank=True, null=True)
    longitude = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'tblsiteaccess'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM