0

I have two models: Feed and User

A User can create a Feed with a POST Method. Other Users can see this feed, and every time a user sees a feed, the feed object should update and save the user's id in 'seen_by_users'.

class User(models.Model):
    registered = models.DateTimeField(auto_now_add=True)
    last_login = models.DateTimeField(auto_now=True)

class Feed(models.Model):
    owner = models.ForeignKey(User, blank=False, related_name='feed_owner')  # required
    feed_message = models.CharField(max_length=255, blank=False, default='')
    created = models.DateTimeField(auto_now_add=True, blank=False)  # required
    seen_by_users = models.ForeignKey(User, blank=True, null=True, related_name='seen_by_users')

in serializers I have:

class FeedSerializer(serializers.ModelSerializer):
    class Meta:
        model = Feed
        fields = ('id', 'owner', 'feed_message', 'created', 'seen_by_users')

    def create(self, validated_data):
        feed = Feed.objects.create(**validated_data)
        return feed

    def update(self, instance, validated_data):
        instance.seen_by_users = validated_data.get('seen_by_users', instance.seen_by_users)
        instance.save()
        return instance

For now, I can just save one user Id to seen_by_users but, how can I change or edit my Model or Serializer to adding an array of users to seen_by_users. It should work when I updating a Feed.

I'm using Django 1.7.1 with Django Rest Framework 3.0.

Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
Miralem Cebic
  • 1,276
  • 1
  • 15
  • 28
  • Just a friendly heads up, _usually_ your `related_name` doesn't match the field name on the model. `User.seen_feeds` may make more sense than `User.seen_by_users` (which makes sense as `Feed.seen_by_users`). – Kevin Brown-Silva Dec 26 '14 at 18:19
  • Sorry I don't understand what you mean. I can't find `Users.seen_by_users`. – Miralem Cebic Dec 26 '14 at 18:27
  • Also, the `Feed.seen_by_users` field should probably be [a many-to-many relationship](https://docs.djangoproject.com/en/stable/topics/db/examples/many_to_many/) instead of a one-to-many. And here's a reference for [the `related_name` attribute on model fields](http://stackoverflow.com/q/2642613/359284). – Kevin Brown-Silva Dec 26 '14 at 18:28

1 Answers1

0

You could create some custom middleware for your app the sets a session with the user's id when they access the view for the feed.Then you can access the id in your view and save it to the database; you'll probably need a many-to-many relationship in your database; e.g. many users can view a feed and vice versa - Middleware info

You may consider creating a Signal for the updating of your database each time a user views a feed - Signals info