django 不同 table 数据合并

django different table data merge

models.py 例如)

table1(models.Model):
   id = primarykey
   content = textfield
   registerdate = datetimefield

table2(models.Model):
   id = primarykey
   content = textfield
   plus1 = charfield
   plus2 = charfield
   registerdate = datetimefield

我试过了

tb2 = table2.objects.all().values("id","content","plus1","plus2","registerdate")
tb1 = table1.objects.all().annotate(plus1=Value('plus1', output_field=CharField()),plus2=Value('plus2', output_field=CharField())).values("id","content","plus1","plus2","registerdate")

合并 = tb2.union(tb1)

tb2 值是正确的

但是 tb 1 字段很奇怪。

有时plus1 = plus1 , plus2=plus2 有时 plus1 = plus2 , plus2=plus1

我要

merge.count()
merge.order_by("-registerdate")

我能否得到一致对齐的字段

如果不是

我可以在没有工会的情况下获得计数和订单吗?

如果你改变你的表结构,你根本不会有这个问题。 考虑以下因素:

table1(models.Model):
   id = primarykey
   content = textfield
   registerdate = datetimefield

table2(table1):
   plus1 = charfield
   plus2 = charfield

如果你这样做,你可以得到表 1 和表 2 的计数 table1.objects.count() 您还可以仅使用 table2.objects.count()

获取 table2 的计数

您还可以使用 OneToOne 字段。这是一个例子:

table1(models.Model):
    id = primarykey
    content = textfield
    registerdate = datetimefield

table2(models.Model):
    id = primarykey
    table1 = models.OneToOne(table1)
    plus1 = charfield
    plus2 = charfield

现在您可以像这样在 table2 上使用 F 对象进行注释

from django.db.models import F
table2.objects.all().annotate(content=F('table1__content'), registerdate =F('table1__ registerdate'))