Search code examples
pythondjangoviewmodels

Django Adding Values to ForeignKey


I'm trying to set up a way for users to "watch" certain items (i.e. add items to a list containing other items by other users):

class WatchList(models.Model):
    user = models.ForeignKey(User)

class Thing(models.Model):
    watchlist = models.ForeignKey(WatchList, null=True, blank=True)

How do I add a Thing to a users WatchList?

>>> from myapp.models import Thing
>>> z = get_object_or_404(Thing, pk=1)
>>> a = z.watchlist.add(user="SomeUser")

  AttributeError: 'NoneType' object has no attribute 'add'

How can I add the item to the watchlist? And/or is this the appropriate way to set up my model fields? Thanks for any ideas!


Solution

  • z.watchlist is the reference itself, it is not a relationship manager. Just assign:

    z.watchlist = WatchList.objects.get(user__name='SomeUser')
    

    Note that this assumes there is only one WatchList per user.