0

使用:

检查空查询集

我有以下代码:

模型.py

from django.db import models

class Currency(models.Model):
    currency_name = models.CharField(max_length=100)
    currency_value_in_dollars = models.FloatField()
    currency_value_in_dollars_date = models.DateField()

    def __str__(self):
        return self.currency_name


class User(models.Model):
    user_name = models.CharField(max_length=200)
    user_pass = models.CharField(max_length=200)
    join_date = models.DateField()

    def __str__(self):
        return self.user_name


class Transaction(models.Model):
    transaction_type = models.CharField(max_length=200)
    transaction_amount = models.FloatField()
    transaction_date = models.DateField()
    transaction_currency = models.ForeignKey(Currency, on_delete=models.CASCADE)
    transaction_users = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.headline

视图.py:

def get_latest_currency(self):
    """
    Return most up to date value
    """
    filtered_currency = Currency.objects.filter(
            currency_value_in_dollars_date__lte=timezone.now()
        ).order_by('-currency_value_in_dollars_date')[:1]

    if not filtered_currency:
        # No objects yet; fetch currencies
        update_coins_table()

即使我没有条目 update_coins_table() 也不会执行。为什么过滤器不能按预期工作?(包含查询结果?)

当达到 if 时,会抛出以下错误:

django.db.utils.ProgrammingError: relation "manage_crypto_currency_currency" does not exist
LINE 1: ...y_currency"."currency_value_in_dollars_date" FROM "manage_cr...

我不知道关系 manage_crypto_currency_currency 是如何创建的,因为该字符串甚至不在代码中。

它很可能与迁移有关:

# Generated by Django 3.1.3 on 2020-11-18 17:58

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Currency',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('currency_name', models.CharField(max_length=100)),
                ('currency_value_in_dollars', models.FloatField()),
                ('currency_value_in_dollars_date', models.DateField()),
            ],
        ),
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('user_name', models.CharField(max_length=200)),
                ('user_pass', models.CharField(max_length=200)),
                ('join_date', models.DateField()),
            ],
        ),
        migrations.CreateModel(
            name='Transaction',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('transaction_type', models.CharField(max_length=200)),
                ('transaction_amount', models.FloatField()),
                ('transaction_date', models.DateField()),
                ('transaction_currency', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='manage_crypto_currency.currency')),
                ('transaction_users', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='manage_crypto_currency.user')),
            ],
        ),
    ]

但是为什么 django 会创建'manage_crypto_currency_currency',因为它显然不是关系。

运行迁移:

(venv) C:\>python manage.py makemigrations manage_crypto_currency
Migrations for 'manage_crypto_currency':
  manage_crypto_currency\migrations\0001_initial.py
    - Create model Currency
    - Create model User
    - Create model Transaction

(venv) C:\>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, manage_crypto_currency, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying manage_crypto_currency.0001_initial... OK
  Applying sessions.0001_initial... OK
4

1 回答 1

2

要检查记录是否存在,您可以使用该exists()方法。见下面的代码:

def get_latest_currency(self):
    """
    Return most up to date value
    """
    filtered_currency = Currency.objects.filter(
            currency_value_in_dollars_date__lte=timezone.now()
        )

    if not filtered_currency.exists():
        update_coins_table()

我希望这能解决你的问题。

于 2020-11-21T20:17:40.137 回答