0
    class Pinyin(models.Model):
    pinyinWord = models.CharField(max_length=200)
    englishWord = models.CharField(max_length=1000)
    englishPhrase = models.TextField()
    pinyinPhrase = models.TextField()
    def __unicode__(self):
        return u"%s | %s" % (self.pinyinWord, self.englishWord)

class Learned(models.Model):
    def __unicode__(self):
        return u"%s | %s | %s | %s" % (self.pinyinWord, self.user, self.date, self.learned) 
    pinyinWord = models.ForeignKey(Pinyin)
    user = models.ForeignKey(User)
    date = models.DateField()
    learned = models.BooleanField()

我是 django 和编程的新手,想将模型拼音的值添加到模型学习,但前提是它还没有被添加到该特定用户的学习中,但似乎无法准确掌握如何做到这一点。

例如,我想从 Pinyin 中获取一个值,如果 Pinyin.id 和 User.id 尚未在 Learned 中,则将单词添加到 Learned 模型中,用户 id、今天日期和学习设置为 False/0。

4

2 回答 2

1

您可以使用模型元选项unique_together

class Learned(models.Model):
    pinyinWord = models.ForeignKey(Pinyin)
    user = models.ForeignKey(User)
    date = models.DateField()
    learned = models.BooleanField()
    class Meta:
        unique_together = ('user', 'pinyinWord')
于 2011-04-17T16:26:46.807 回答
0

我希望这是你正在寻找的:

uid = User.objects.get(username='Greg').id
pinyin = Pinyin.objects.get(pinyinWord='kuai')

learned, created = Learned.objects.get_or_create(pinyinWord=pinyin.pinyinWord, 
                                                                 user__id=uid)
if created:   # newly INSERTed Learned  instance
     learned.date = datetime.date.today()
     learned.learned = False
     learned.save()

Model.objects.get_or_create方法首先尝试使用提供的参数调用Model.objects.get 。如果失败,对象将被创建并且创建为True,否则创建为False。

由于这是对两个字段的精确查找(例如不是 pinyinWord__contains),因此当没有满足两个字段的 Learned 实例时,它将失败。然后它被创建。

之后,您可以设置日期等并保存实例。

于 2011-04-17T16:43:47.580 回答