0

I have the following model that basically stores a random hash value for each tag associated with a particular user.

class PublicTags(models.Model):
    tag = models.ForeignKey(Tag, related_name='hashes')
    hash_value = models.CharField(max_length=103)
    user = models.ForeignKey(User, related_name='tags')
    public = models.BooleanField(default=False)

    class Meta:
        unique_together = ('tag', 'user')
        verbose_name_plural = 'Public Tag Hashes'

    def __unicode__(self):
        return u'%s: %s' % (self.tag, self.user, self.hash_value)

I am trying to use the Django Rest Framework to do the following:

  • Create a view that will be accessed at api/v1/public_tags.
  • I will use AJAX to post data using the Django Rest API.
  • On a post, the system does the following: It checks to see if there is already a Public Tag row for the tag id (sent via post) If not, it creates a random hash_value for that tag and user.

I am confused about how to use the Django Rest Framework to accomplish this task.

I got this far:

class PublicTagView(RetrieveUpdateAPIView):
    model = PublicTags
    serializer_class = serializers.PublicTagSerializer
    permission_classes = (IsAuthenticated,)

class RetrieveUpdateAPIView(mixins.RetrieveModelMixin,
                            mixins.UpdateModelMixin,
                            generics.SingleObjectAPIView):
    """
    Concrete view for retrieving or updating a model instance.
    FIXME: the newest version of rest_framework has this class
    """

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def create(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

1 Answer 1

1

As far as I understand you need to query an individual record and create a record. In this case generic class based views are fine enough to start with.

You can then map these views in your urls.py like this:

urlpatterns = patterns('',
    url(r'^api/v1/public_tags/$', views.PublicTagsList.as_view()),
    url(r'^api/v1/public_tags/(?P<pk>[0-9]+)/$', views.PublicTagsDetail.as_view()),
)

This is valid if you use primary key to fetch individual record.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.