帮助处理Django模型关系


    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中,然后将用户id,今天的日期和学习设置为False/0的单词添加到Learned模型中。

您可以使用模型元选项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')

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

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调用提供的参数。如果失败,对象将被创建,created为True,否则created为False。

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

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

相关内容

  • 没有找到相关文章

最新更新