Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 664
Nick B Avatar asked Oct 21 '13 17:10

Nick B


People also ask

What is the difference between ForeignKey and OneToOneField?

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 .

How do I create a one to many relationship in Django?

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).

How does ForeignKey work in Django?

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.


2 Answers

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.

like image 158
Martijn Pieters Avatar answered Sep 22 '22 15:09

Martijn Pieters


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.

like image 38
SColvin Avatar answered Sep 25 '22 15:09

SColvin