我有一个链接和一个书签模型像这样:
class Link(models.Model):
url = models.URLField(unique=True)
def __unicode__(self):
return self.url
class Bookmark(models.Model):
title=models.CharField(max_length=200)
user=models.ForeignKey(User)
link=models.ForeignKey(Link)
def __unicode__(self):
return u %s, %s % (self.user.username, self.link.url)
Now within a view I see if a Link with a given url already exists. This object is then passed next with the username to Bookmarks collection to see if a bookmark already exists with this username and Link instance already exists.
def bookmark_save_page(request):
if request.method == POST :
form = BookmarkSaveForm(request.POST)
if form.is_valid():
# Create or get Link
link, dummy = Link.objects.get_or_create(url=form.cleaned_data[ url ])
# Create or get bookmark
bookmark, created = Bookmark.objects.get_or_create(user=request.user, link=link)
# Save bookmark to database
bookmark.save()
return HttpResponseRedirect( /user/%s/ % request.user.username)
这是部分我不明白的。 它怎么知道如何将 Link 模型中的 URL 字段作为比较的方法? 是因为我在 Link 模型中定义了它吗?
def __unicode__(self):
return self.url
我来自.NET,你必须给班级定义GetHash(), 以说明如何比较情况。
How does Python know this? Thanks