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()
I am new to django and programming for that matter and want to add a value from Model Pinyin to Model Learned but only if it has not already been added to learned for that specific user but can't seem to grasp exactly how to do this.
For example, I want to grab a value from Pinyin and if Pinyin.id and User.id are not already in Learned, then add the word to the Learned model with the user id, todays date and learned set to False/0.
You could use the model meta option 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')
I hope this is what you are looking:
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()
The Model.objects.get_or_create method first tries a Model.objects.get call with the provided arguments. If it fails, the object will be created and created will be True, otherwise created is False.
Since this is an exact lookup (not pinyinWord__contains for example) for both fields, it will fail when there is no Learned instance that satisfies both fields. Then it gets created.
After that you can set the date and so on and save the instance.
精彩评论