【问题标题】:objects.all() not returning any objects in Djangoobjects.all() 在 Django 中不返回任何对象
【发布时间】:2015-03-30 05:49:03
【问题描述】:

我在models.py中有以下模型:

from django.contrib.auth.models import User
from django.db import models

class Usertypes(models.Model):
    user = models.OneToOneField(User)
    usertype = models.TextField()                   

    def __unicode__(self):
        return self.user_name

class Games(models.Model):
    name = models.CharField(max_length=100,unique=True)
    category = models.CharField(max_length=100)
    url = models.URLField()
    developer = models.ForeignKey(User)
    price = models.FloatField()

    def __unicode__(self):
        return self.name

class Scores(models.Model):
    game = models.ForeignKey(Games)
    player = models.ForeignKey(User)
    registration_date = models.DateField(auto_now=False, auto_now_add=False)
    highest_score = models.PositiveIntegerField(null=True,blank=True)
    most_recent_score = models.PositiveIntegerField(null=True,blank=True)

    def __unicode__(self):
        return self.most_recent_score

我现在正在创建所有 3 种类型的对象。我之前已经创建了一些 User 和 Games 对象,所以当我运行以下命令时,将获得如下输出:

>>> u = User.objects.all()
>>> u.count()
5
>>> g = Games.objects.all()
>>> g.count()
9

现在,我正在尝试使用以下命令创建一些分数对象。输出如下:

>>> fifa = Games.objects.get(pk=18)
>>> user1 = User.objects.get(id=2)
>>> user2 = User.objects.get(id=7)
>>> user3 = User.objects.get(id=9)
>>> p1 = Scores(game=fifa,player=user1,registration_date='2015-01-29')
>>> p2 = Scores(game=fifa,player=user2,registration_date='2014-12-21')
>>> p3 = Scores(game=fifa,player=user3,registration_date='2015-01-29')
>>> user1
<User: admin>
>>> fifa
<Games: Games object>
>>> p1
<Scores: Scores object>
>>> p2
<Scores: Scores object>
>>> p3
<Scores: Scores object>

问题是:

>>> s = Scores.objects.all()
>>> s.count()
0

我不明白为什么,尽管创建了 3 个 Scores 对象,Scores.objects.all() 却什么也没返回。有人可以帮忙吗?提前致谢!!

【问题讨论】:

  • 您忘记保存创建的Score 对象
  • 我完全忽略了这一点。谢谢!!

标签: python django django-models


【解决方案1】:

您从未将分数插入数据库(因此数据库当然无法将它们返回给您):

p1.save()  # This will save the object to the database

请注意,您也可以使用Scores.objects.create(...)(而不是Score())。这将初始化一个对象并立即将其保存到数据库中:

p1 = Scores.objects.create(game=fifa,player=user1,registration_date='2015-01-29')

现在这些方法将导致对数据库进行三个查询,这并不理想(您达到了 3 次往返延迟)。

幸运的是,您可以使用bulk_create 轻松优化和进行单个查询:

Scores.objects.bulk_create([
    Scores(game=fifa,player=user1,registration_date='2015-01-29')
    Scores(game=fifa,player=user2,registration_date='2014-12-21')
    Scores(game=fifa,player=user3,registration_date='2015-01-29')
])

【讨论】:

    【解决方案2】:

    确保您正在运行 .save(),它实际上将项目保存在数据库中。没有它,您就不会在数据库中保存任何内容,因此当您从数据库中检索对象时,您什么也得不到

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      相关资源
      最近更新 更多