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!
A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True , but the "reverse" side of the relation will directly return a single object. In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns a QuerySet .
To define a one to many relationship in Django models you use the ForeignKey data type on the model that has the many records (e.g. on the Item model).
Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.
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.
As karthikr said you may be getting confused with manytomanyfield, if you really want an intermediary model, you might have something like this:
# Models:
class WatchList(models.Model):
user = models.ForeignKey(User, related_name='watchlists')
class Thing(models.Model):
watchlist = models.ForeignKey(WatchList, null=True, blank=True)
# Usage:
user = User.objects.get(name='???') # or obtain the user however you like
wl = WatchList.objects.create(user=user)
thing = Thing.objects.get(id=1) # or whatever
thing.watchlist = wl
thing.save()
# get users watch lists:
user.watchlists
...
Otherwise you might want to extend the user model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With