我有一个表,其中有一列存储值列表。这些值基本上是另一个表的外键值。
表格是:
groups (
id TEXT PRIMARY KEY,
users TEXT [],
name TEXT NOT NULL,
user_count INT NOT NULL,
group_type TEXT NOT NULL CHECK (group_type IN ('random', 'friends')) DEFAULT 'random',
validity_period INT NOT NULL,
user_add_time INT NOT NULL,
winner TEXT [],
energy_drink_fee INT DEFAULT 0,
energy_bar_fee INT DEFAULT 0,
winnings INT DEFAULT 0, -- can be 0 (for free tournaments), 40, 150 (for paid tournaments)
created_at TIMESTAMP DEFAULT now(),
updated_at TIMESTAMP DEFAULT now()
);
在Django中,它是:
class Groups(models.Model):
id = models.TextField(primary_key=True)
users = ArrayField(blank=True, null=True, base_field=models.CharField)
name = models.TextField()
user_count = models.IntegerField()
group_type = models.TextField()
validity_period = models.IntegerField()
user_add_time = models.IntegerField()
winner = ArrayField(blank=True, null=True, base_field=models.CharField)
energy_drink_fee = models.IntegerField(blank=True, null=True)
energy_bar_fee = models.IntegerField(blank=True, null=True)
winnings = models.IntegerField(blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
'users'和'winners'是存储User表的id的列(username是id)。
我没有更改数据库,表格是相同的,除了我使用Django读取此数据库(Legacy DBs)。我仍然不确定ArrayField。
这是我在SQL中编写的查询:
SELECT COUNT(g.*) AS match_count, TEXT(g.created_at::DATE) AS created_at
FROM groups g
JOIN users u ON u.username = ANY (g.winner)
WHERE g.created_at::DATE >= '2018-01-01' AND g.created_at::DATE <= '2018-01-20'
AND g.winnings = 0 AND g.group_type = 'random' AND u.type = 'u'
AND g.winner IS NOT NULL
GROUP BY g.created_at::DATE
我需要将此查询迁移到Django的ORM中。 如何使用此数组字段(获胜者)进行连接?