How can we create object in desire database in rest framework - python

I'm creating project but that project is saving in the default database. I want to create that project in other database... I'm using CreatApiView..
class CreateProjectAPIView(generics.CreateAPIView):
"""This endpoint allows for creation of a Project"""
queryset = Project.objects.using('notification_dev').all()
serializer_class = serializers.ProjectSerializer
def get_serializer(self, *args, **kwargs):
serializer_class = self.get_serializer_class()
kwargs["context"] = self.get_serializer_context()
draft_request_data = self.request.data.copy()
print("draft_request_data :",draft_request_data)
kwargs["data"] = draft_request_data
return serializer_class(*args, **kwargs)
I don't get it how can i use that .using("otherdataName") in get_serializer

Well, you can not (or you shouldn't) be performing database operations in get_serializer.
The execution flow goes like this:
view.create --> serializer.save --> serializer.create --> model.save
So, editing the model.save function is the preferred option. The only downside to that is during bulk_create but you aren't using that.
Look at the following code from Django documentation:
Model.save(force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None)ΒΆ
So, updating using there will be efficient.

Related

How to manually populate a relational model in Django REST

I'm still new to Django and DRF. I have 2 models (Policy and Rescue) and Rescue is related to Policy by the Foreign Key policy_id. I have no issue to POST a JSON message and get Policy populated with the request data by CreateView. However, the 2nd model Rescue needs be populated based on some calculations from the JSON data POSTed to the Policy. Rescue cannot be POSTed beforehand. I tried hard but had no clue to do so.
Is this something to do with nested serializer or something else?
I've tried to
Can I try this way: inside the class CreateView:
class CreateView(generics.CreateAPIView):
def create(self, request, *args, **kwargs):
my_serializer = self.get_serializer(data=request.data)
...
# get a policy object based on 'policy_id' against serializer
my_policy = Policy.objects.get(policy_id=my_serializer.data['policy_id'])
...
... # some calculations to work out a rescue id, and will be returned and saved.
Rescue.objects.create(rescue_id='QD1234', policy=my_policy)
you can use a generic CreateAPIView and override the perform_create method.
def perform_create(self, serializer):
my_policy = serializer.save()
# you custom calculation for rescue_id
rescue_obj = Rescue.objects.create(rescue_id='QD1234', policy=my_policy)
perform create method is documented here: https://www.django-rest-framework.org/api-guide/generic-views/#methods

Custom function which performs create and update on DRF modelViewSet

Hi there I want to create a custom method in a modelviewset which needs to perform a save and an update logic in a single post request.
Here is my breeding.viewsets.py
class BreedingViewSet(viewsets.ModelViewSet):
queryset = Breeding.objects.all()
serializer_class = BreedingSerializer
Since the above method has a higher level of abstraction and is
actually providing or performing automatic CRUD functions.
Now the problem here is i dont have any control for a multiple queries like saving an object and updating another object in a single post request.
e.g
def save_and_update(self, request):
// do save an object here.
// do update an object here.
How can we achieve such powerful functionalities? Did i missed something? I found this documentation but i dont know how to implement the given instruction.
UPDATE
This is what im looking for How do I create multiple model instances with Django Rest Framework?
But the answer can only save a multiple instances in a single post request of that same model. But Im hoping also that we can perform queries for a different models in that single function.
Well, from the comments, it looks like you want to update some unrelated model when you create your breeding model. This should be easy.
class BreedingViewSet(viewsets.ModelViewSet):
queryset = Breeding.objects.all()
serializer_class = BreedingSerializer
def create(self, request):
# do your thing here
return super().create(request)
Use this to create or update using POST
class BreedingViewSet(viewsets.ModelViewSet):
queryset = Breeding.objects.all()
serializer_class = BreedingSerializer
def get_object(self):
if self.action == 'create':
queryset = self.filter_queryset(self.get_queryset())
filter_kwargs = {self.lookup_field: self.request.data.get('id')}
obj = get_object(queryset, **filter_kwargs)
self.check_object_permissions(self.request, obj)
return obj
else:
return super(BreedingViewSet, self).get_object()
def create(self, request, *args, **kwargs):
if request.data.get('id'):
return super(BreedingViewSet, self).update(request, *args, **kwargs)
else:
return super(BreedingViewSet, self).create(request, *args, **kwargs)

django model save - override method not invoked during migrations

I have a save override method in my model class, which generates a new slug each time an object is saved.
def save(self, *args, **kwargs):
if self.column2:
self.slug = slugify(self.column1 + " " + self.column2)
else:
self.slug = slugify(self.column1)
print slug
super(MyModel, self).save(*args, **kwargs)
When I try to create a new object by logging into the python shell, I see the save method is being invoked.
python manage.py shell
>>> MyModel(column1="test",column2="2015").save()
slug is test-2015
However when I am running a migration, this save override method is not being called. Here's part of my migration script..
...
def add_myModel_details(apps, schema_editor):
x = apps.get_model("myapp","myModel")
MyModel(column1 = "test", column2="2015" ).save()
.....
The slug is empty, as the save override isn't being called.
Custom model methods are not available during migrations.
Instead, you can run put code in your RunPython function that modifies your model instances the way the custom save() would have.
References:
This answer
It happens because migrations don't call your save method.
I think save method is not the best place for generate slug. Will be better to use AutoSlugField or signals.
1. signals:
In your case you may use signal pre_save.
Example:
#receiver(pre_save, sender=MyModel)
def my_handler(sender, **kwargs):
my_model = kwargs.get('instance')
if my_model.column2:
my_model.slug = slugify(my_model.column1 + " " + my_model.column2)
else:
my_model.slug = slugify(my_model.column1)
print my_model.slug
2. AutoSlugField:
It's not a standard field but a lot of libraries implement it. I use AutoSlugField from django-extensions. This field uses signals too.
Example:
slug = AutoSlugField(populate_from=("column1", "column2"))
3. save method and migrations
But if you still want to use a save method to generating slug I'd recommend you create data migration and add slugs manually.
Data Migrations django >= 1.7
Data Migrations south

How can I PUT/POST JSON data to a ListSerializer?

I'm reading about customizing multiple update here and I haven't figured out in what case the custom ListSerializer update method is called. I would like to update multiple objects at once, I'm not worried about multiple create or delete at the moment.
From the example in the docs:
# serializers.py
class BookListSerializer(serializers.ListSerializer):
def update(self, instance, validated_data):
# custom update logic
...
class BookSerializer(serializers.Serializer):
...
class Meta:
list_serializer_class = BookListSerializer
And my ViewSet
# api.py
class BookViewSet(ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
And my url setup using DefaultRouter
# urls.py
router = routers.DefaultRouter()
router.register(r'Book', BookViewSet)
urlpatterns = patterns('',
url(r'^api/', include(router.urls)),
...
So I have this set up using the DefaultRouter so that /api/Book/ will use the BookSerializer.
Is the general idea that if I POST/PUT/PATCH an array of JSON objects to /api/Book/ then the serializer should switch over to BookListSerializer?
I've tried POST/PUT/PATCH JSON data list to this /api/Book/ that looks like:
[ {id:1,title:thing1}, {id:2, title:thing2} ]
but it seems to still treat the data using BookSerializer instead of BookListSerializer. If I submit via POST I get Invalid data. Expected a dictionary, but got list. and if I submit via PATCH or PUT then I get a Method 'PATCH' not allowed error.
Question:
Do I have to adjust the allowed_methods of the DefaultRouter or the BookViewSet to allow POST/PATCH/PUT of lists? Are the generic views not set up to work with the ListSerializer?
I know I could write my own list deserializer for this, but I'm trying to stay up to date with the new features in DRF 3 and it looks like this should work but I'm just missing some convention or some option.
Django REST framework by default assumes that you are not dealing with bulk data creation, updates, or deletion. This is because 99% of people are not dealing with bulk data creation, and DRF leaves the other 1% to third-party libraries.
In Django REST framework 2.x and 3.x, a third party package exists for this.
Now, you are trying to do bulk creation but you are getting an error back that says
Invalid data. Expected a dictionary, but got list
This is because you are sending in a list of objects to create, instead of just sending in one. You can get around this a few ways, but the easiest is to just override get_serializer on your view to add the many=True flag to the serializer when it is a list.
def get_serializer(self, *args, **kwargs):
if "data" in kwargs:
data = kwargs["data"]
if isinstance(data, list):
kwargs["many"] = True
return super(MyViewSet, self).get_serializer(*args, **kwargs)
This will allow Django REST framework to know to automatically use the ListSerializer when creating objects in bulk. Now, for other operations such as updating and deleting, you are going to need to override the default routes. I'm going to assume that you are using the routes provided by Django REST framework bulk, but you are free to use whatever method names you want.
You are going to need to add methods for bulk PUT and PATCH to the view as well.
from rest_framework.response import Response
def bulk_update(self, request, *args, **kwargs):
partial = kwargs.pop("partial", False)
queryset = self.filter_queryset(self.get_queryset))
serializer = self.get_serializer(instance=queryset, data=request.data, many=True)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response(serializer.data)
def partial_bulk_update(self, *args, **kwargs):
kargs["partial"] = True
return super(MyView, self).bulk_update(*args, **kwargs)
This won't work out of the box as Django REST framework doesn't support bulk updates by default. This means you also have to implement your own bulk updates. The current code will handle bulk updates as though you are trying to update the entire list, which is how the old bulk updating package previously worked.
While you didn't ask for bulk deletion, that wouldn't be particularly difficult to do.
def bulk_delete(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
self.perform_delete(queryset)
return Response(status=204)
This has the same effect of removing all objects, the same as the old bulk plugin.
None of this code was tested. If it doesn't work, consider it as a detailed example.

How can I test post-save, pre-save in the full system testing in Django with REST

I have the application in Django REST as backend and Angular as frontend.
Suppose in This is my code
class ModelClass (models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
def save(self, *args, **kwargs):
#check if the row with this hash already exists.
if not self.pk:
self.hash = self.create_hash()
self.my_stuff = 'something I want to save in that field'
# call to some async task
super(ModelClass, self).save(*args, **kwargs)
In my REST i have this view
class ModelListCreateView(generics.ListCreateAPIView):
model = ModelClass
serializer_class = ModelClassSerializer
def pre_save(self, obj):
obj.created_by = obj.updated_by = self.request.user.staff
def post_save(self, obj, created=False):
# add some other child objects of other model
I don't want to do unit testing. I want to do system testing so that I need to know if I post something to that view then
Pre-save thing should work
Record gets created
Save method of Model gets called with his stuff
After save method in REST gets called
Then I can assert all that stuff.
Can I test all that . I want to know which thing I need to have that sort of test rather than small unit tests
I am confused do I need to use Django test or REST Test or selenium test or PyTEst or factory boy because i want to know if things are actually getting in database
What you are looking is some kind of a REST Client code that would then be able to run your tests and you would be able to verify if the call is successful or not. Django Rest Framework has the APIRestFactory helper class that will aid you in writing such tests. The documentation can be found here and specifically look at the Example section. This would be part of your Django tests

Categories

Resources