I have a Link and a Bookmark model like this:
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)
This is the bit I don’t understand. How does it know how to take the url field inside Link model as a way of comparison? Is it because I had defined it in the Link model like this?
def __unicode__(self):
return self.url
I am coming from .NET and there you have to define the GetHash() for the class as a way to specify how the instances should be compared against each other.
How does Python know this?
Thanks
I think you are asking “how does Django compare instances when filtering”, rather than “how does python compare objects”.
With the following line of code,
Django is filtering on link object’s primary key. The
__unicode__method does not matter.See the Django docs for comparing objects and queries over related objects for more info.