Django Rest Framework CRUD - django

I´m building an API with Django Rest Framework, and I’m wondering if it's enough to use only the ModelViewSet class to implement the CRUD. My worries is that it’s not enough for the frontend to consume and use the create, read, update and delete functionalities.

For a short answer, "yes".
But, I would suggest you to read the official docs from DRF.
ModelViewSet's docs
The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes.
The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy().
GenericAPIView's docs
This class extends REST framework's APIView class, adding commonly required behavior for standard list and detail views.
Each of the concrete generic views provided is built by combining GenericAPIView, with one or more mixin classes.
--
There are also plenty of blogs explaining why and when to use these class.
Django Rest Framework ViewSets
--
Lastly, I'm new to the community just like you did. I'm not sure this kind of question would be allowed here or not. But, what I'm trying to say is..
Stop worrying, just go and try out yourself. I believe that people in the community would willing to help you out if you've stuck.

Related

What is the difference between mixins and generics?

I'm learning about the Django Rest Framework. And there are two concepts that from my point of view are almost the same, and they are used in different scenarios.
rest_framework mixins I think that they are used when we use viewsets.
And rest_framework generics are used with APIViews.
What is the difference between these two components?
The generics and mixin modules are indeed different, yet they are inter-related.
Django Rest Framework (DRF) separates ReSTful API / HTTP verb behaviour from Django model operations and organises a set of abstract/base classes for each. The ReSTful functionality is in APIView, GenericAPIView and ViewSetMixin. The Model related operations are implemented in the mixin module.
DRF then makes use of Python's multiple inheritance, and the "mixin" pattern, to combine these together into higher-level classes that are both useable and extensible.
The generic views and the concrete ModelViewSet both inherit from APIView in addition to composing functionality via the mixin classes.
Though not related to the question, the following observation about ViewSets may be helpful...
The following is the intro to ViewSets on the DRF site that might make things seem more complicated than they really are...
A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create().
The method handlers for a ViewSet are only bound to the corresponding actions at the point of finalizing the view, using the .as_view() method.
Rather than inheriting the ViewSet directly, in many cases, it will make the most sense to inherit a ModelViewSet and combine it with a DefaultRouter. The ModelViewSet obtains the method handlers via the various mixin classes, and the DefaultRouter provides the 'action' function mapping.
In combination, all the basic REST actions can be performed on a given Model, with very little code.

Django Rest Framework -A concrete example of when you would use a serializer class vs a model serializer class

I am learning django rest framework, while I understand what a serializer does and when you would use it, I cannot fully seat the need for a serializer and a model serialzer class. Can one of you please give me a concrete real world example use case of both please?
Yes I have gone through the tutorial on DRF website several times and I still am experiencing fuzziness
There is an excellent example on the DRF tutorial and it would take too much to cover in an answer, but I would like to make some points.
First, the DRF documentation explains:
Our SnippetSerializer class is replicating a lot of information that's also contained in the Snippet model. It would be nice if we could keep our code a bit more concise.
In the same way that Django provides both Form classes and ModelForm classes, REST framework includes both Serializer classes, and ModelSerializer classes.
The Snippet model is the name of the model used in that example. So as the documentation says, rather than typing again the same fields from the model over to a Serializer, we can use a ModelSerializer as a shortcut, in a similar way that we would use a ModelForm over a simple Form.
But this leaves the question essentially as "ok, then why is there a simple Serializer class at all?", as you pointed out in your comment.
In the vast majority of cases where you have models and you need to serialize/deserialize relevant data (usually JSON but not limited to), then ModelSerializer is the way to go. Even if additional fields, related serializers or arbitrary logic is required, a ModelSerializer can be easily tweaked. Personally it has never occured to me with any of my projects that ModelSerializer is not suitable for data related to a model.
But there may be cases where you need to handle data that do not abide to a model. Such data would be POSTed to a DRF view and a Serializer would handle them. Such cases could be for example to send a mail message, to setup a Celery task, to add data to session, and many others that do not involve a model at all.

Creating nested objects in Django REST Framework

What is the right™ way to design DRF serializers that receive the following POSTed data to a List model:
{
list_name: "friends",
contacts: ["alice", "bob"]
}
And handles the creation of the nested Contact objects? Additionally, assume an extra step is needed to convert the names to capitalized (['Alice', 'Bob']).
You could use django-rest-framework-bulk which is linked from Django Rest Framework's documentation: http://www.django-rest-framework.org/topics/third-party-resources#views
'Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.'
I'm not sure if it's the 'right™' way of doing it but the library is being actively maintained and it's 9 months old and seems to have a few contributors. Worth looking into.

Django design patterns for overriding models

I'm working on an e-commerce framework for Django. The chief design goal is to provide the bare minimum functionality in terms of models and view, instead allowing the users of the library to extend or replace the components with their own.
The reasoning for this is that trying to develop a one-size-fits-all solution to e-commerce leads to overcomplicated code which is often far from optimal.
One approach to tackling this seems to be using inversion-of-control, either through Django's settings file or import hacks, but I've come up against a bit of a problem due to how Django registers its models.
The e-commerce framework provides a bunch of abstract models, as well as concrete versions in {app_label}/models.py. Views make use of Django's get_model(app_label,model) function to return the model class without having to hard-code the reference.
This approach has some problems:
Users have to mimic the structure of the framework's apps, ie the app_label and effectively replace our version of the app with their own
Because of the way the admin site works by looking for admin.py in each installed app, they have to mimic or explicitly import the framework's admin classes in order to use them. But by importing them, the register method gets called so they have to be unregistered if a user wants to customise them.
The user has to be extremely careful about how they import concrete models from the core framework. This is because Django's base model metaclass automatically registers a model with the app cache as soon as the class definition is read (ie upon __new__), and the first model registered with a specific label is the one you're stuck with. So you have to define all your override models BEFORE you import any of the core models. This means you end up with messy situations of having a bunch of imports at the bottom of your modules rather than the top.
My thinking is to go further down the inversion-of-control rabbit hole:
All references to core components (models, views, admin, etc) replaced with calls to an IoC container
For all the core (e-commerce framework) models, replace the use of Django's base model metaclass with one that doesn't automatically register the models, then have the container explicitly register them on startup.
My question:
Is there a better way to solve this problem? The goal is to make it easy to customise the framework and override functionality without having to learn lots of annoying tricks. The key seems to be with models and the admin site.
I appreciate that using an IoC container isn't a common pattern in the Django world, so I want to avoid it if possible, but it is seeming like the right solution.
Did you look at the code from other projects with a similar approach?
Not sure if this way covers your needs, but imo the code of django-shop is worth to look at.
This framework provides the basic logic, allowing you to provide custom logic where needed.
customize via models
eg see the productmodel.py
#==============================================================================
# Extensibility
#==============================================================================
PRODUCT_MODEL = getattr(settings, 'SHOP_PRODUCT_MODEL',
'shop.models.defaults.product.Product')
Product = load_class(PRODUCT_MODEL, 'SHOP_PRODUCT_MODEL')
customize via logic/urls
eg see the shop's simplevariation-plugin
It extends the cart-logic, so it hooks in via urlpattern:
(r'^shop/cart/', include(simplevariations_urls)),
(r'^shop/', include(shop_urls)),
and extends the views:
...
from shop.views.cart import CartDetails
class SimplevariationCartDetails(CartDetails):
"""Cart view that answers GET and POSTS request."""
...
The framework provides several points to hook-in, the simplevariation-plugin mentionned above additionally provides a cart-modifier:
SHOP_CART_MODIFIERS = [
...
'shop_simplevariations.cart_modifier.ProductOptionsModifier',
...
]
I worry that this explanation is not very understandable, it is difficult to briefly summarize this concept. But take a look at the django-shop project and some of its extensions: ecosystem

Sharing view logic in Django

I've begun diving into Django again and I'm having trouble finding the parallel to some common concepts from my life in C#. While using .NET MVC I very often find myself creating a base controller which will provide a base action implementation to take care of the type of stuff I want to do on every request, like retrieving user information, getting localization values.
Where I'm finding myself confused is how to do this in Django. I am getting more familiar with the MVT concept but I can't seem to find how to solve this scenario. I've looked at class based views and the generic views yet they didn't seem to work how I expected. What am I missing? How can i create default logic that each view will be instructed to run but not have to write it in each view method?
If it is truly common for your whole site you use middleware. If it is only common for some views, the way to go in my opinion is to create decorators for those views. I never use class-based views because I tend to keep views simple and put more logic into models, so I have no need for classes there.