how to pass null value to just one specific key of the one object using same DRF serializer
I'm just passing the same object 2 times in the same serializer but I want to pass key: "retweet": null in one object and in another object I want to pass some values like some many-to-many field values because key "retweet" is many-to-many field and having data
Thanks in advance!
do you know?
how many words do you know
See also questions close to this topic
-
Upload file from html when block public access is true
I am using
django-s3direct
to file uploadhttps://github.com/bradleyg/django-s3direct
Using IAM role setting because I upload the file from the server on ECS container.
Now I set the
blockPublicAccess
ofS3
false.When uploading images from html, there comes error.
https://s3.ap-northeast-1.amazonaws.com/static-resource-v/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg?uploads (403 (Forbidden) ) initiate error: static-resource-v/line-assets/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg AWS Code: AccessDenied, Message:Access Deniedstatus:403
OK, it is understandable.
Browser try to access the for initiation.
However there is any way to upload file from browser when blockPublicAccess is true??
-
Test a decorated function in Python
I have a python function which is decorated.
@retry_if_access_token_expired(app_id) def add_something( self, *, argument1, argument1 = None, ): """adding something"""
I've written tests for the given as below.
@patch("other inside function to mock") @patch("other insdie function to mock 2") def test_add_something( self, mock_1, mock_2 ): """ some logic to test the add something method """
But I am getting this error that says add_somehthing takes 1 positional argument.
TypeError: add_something() takes 1 positional argument but 3 were given
-
Django Rest Framework ignoring custom field
I have a model with a nullable boolean field that I'd like to have serialized in a way that converts
null
in the output tofalse
.My model:
class UserPreferences(models.Model): receive_push_notifications = models.BooleanField( null=True, blank=True, help_text=("Receive push notifications))
I'm trying to do it with a custom field like so:
class StrictlyBooleanField(serializers.Field): def to_representation(self, value): # Force None to False return bool(value) def to_internal_value(self, data): return bool(data) class UserPreferencesSerializer(serializers.ModelSerializer): class Meta(object): model = UserPreferences fields = ('receive_push_notifications',) receive_push_notifications = StrictlyBooleanField()
but this isn't working, I'm still seeing
null
in my API responses.I think I must be missing something simple in wiring it up because I don't even get an error if I replace my
to_representation
with:def to_representation(self, value): raise
DRF doesn't seem to be calling my method at all... What am I missing here?
-
Django Limit the Number of objects in a model
i am working on a django-cms project and (i have to make a image model which can only make 3 objects not more than that if someone tries there should be a message: Max Objects Have been Created) so, how can i limit the number of objects in a model ? Thank you, I will Really appreciate you feedback.
-
DRF how to update, create OneToOneField in serializers?
I have two models, with OnetoOne field. How can I update/create them with help of serializers?
class Page(models.Model): info = models.TextField(null=True, blank=True) document = models.OneToOneField( Document, primary_key=True, related_name='page', on_delete=models.CASCADE) class Document(models.Model) description = models.TextField(null=True, blank=True) note = models.TextField(null=True, blank=True)
My serializer
class PageSerializer(ModelSerializer): document = DocumentSerializer() class Meta: model = Page fields = ('document', 'info') def update: def create:
-
Django dumpdata serializing an int as string
I've been trying to make a custom class/type, defined in a separate db.py file, to be properly serialized as an int when doing a
manage.py dumpdata
command, but this BitFlagField always ends up exported as a string, the value accompanied by double quotes, while other integer fields are properly exported without the quotes in the JSON file. The person that made it left the place almost a year ago, so I can't get any help from him.This is the class' code - note that I've fixed the
__str__
function and also changed the__repr__
toreturn repr(self.value)
This is how it looks after the dumpdata:
(...), "blocked": "8"}}
; For comparison, two other integer fields don't come with the value enclosed by quotes:"pk": 1, "bit":8,
. Because of this,manage.py loaddata
fails:django.core.serializers.base.DeserializationError: Problem installing fixture '/home/abcd/djangoapp/data.json': '>=' not supported between instances of 'str' and 'int': (core.userextra:pk=1) field_value was '8'
If I manually remove the quotes from the "blocked" field's value, the loaddata command works.
If I delete both
__str__
and__repr__
functions, the object type is what ends up as the data:(...), "blocked": "<core.db.BitFlag object at 0x7f9f2eb0bf40>"}}
. If I make either of them returnself.value
, it complains that it was expecting a str type.What I need is to either save that value as an int in the JSON, which so far I haven't managed to, or deserialize it somewhere, but I can't figure out the where part, as, in my mind, that should be a simple
return int(self.value)
. -
Want to send extra data from BasePermission to Queryset in ModelVIewSet DRF
Here is My Seller Model which has User as OneToOneField
#models.py . . class CompanyProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user") company = models.CharField(max_length=255) pincode = models.IntegerField() city = models.ForeignKey(City, on_delete=models.CASCADE) address = models.TextField() profileActive = models.BooleanField(default=False) . .
Purchase Model
#models.py class PurchaseOrder(models.Model): company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE) message = models.TextField(blank=True, null=True) expectedDelivery = models.DateField(blank=True, null=True) isCancel = models.BooleanField(default=False)) updated_at = models.DateTimeField(auto_now=True)
#Custom permission_classes
class SellerCompanyActive(BasePermission): message = 'Only Seller with activated company account is allowed' def has_permission(self, request, view): user = AuthUser.objects.get(id=request.user.id) if user.is_seller: try: company = CompanyProfile.objects.get(user=user) if company.profileActive: return True else: self.message = "Company profile is not active" except CompanyProfile.DoesNotExist: self.message = "Company not found first create company" return False
In ModelViewSet
#views.py class SellerPurchaseOrder(viewsets.ModelViewSet): queryset = PurchaseOrder.objects.all() serializer_class = PurchaseOrderSerializer authorization_classes = [TokenAuthentication] permission_classes = [IsAuthenticated, SellerCompanyActive] def get_queryset(self): user = self.request.user company = CompanyProfile.objects.get(user=user) return self.queryset.filter(company=company)
Now here I always had to use this
user = self.request.user company = CompanyProfile.objects.get(user=user)
As their are lot of other views also, Is their any other way to send data from my custom permission_classes i.e from SellerCompanyActive to direct SellerPurchaseOrder->get_queryset
-
DRF using prefetch_related
I have two classes Vessels and Components, each vessel has several components. I just want to fetch all vessels and all their related components in one query, I thought prefretch_related does that trick but in DRF in the api i am only receiving the vessels without their related components
models.py
class Vessel(models.Model): name = models.CharField(max_length=255, null=True, blank=True) imo = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.name class Component(models.Model): vessel = models.ForeignKey( Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_components') name = models.CharField(max_length=200, blank=True, null=True) manufacturer = models.CharField(max_length=200, blank=True, null=True) model = models.CharField(max_length=200, blank=True, null=True) type = models.CharField(max_length=200, blank=True, null=True) remarks = models.TextField(blank=True, null=True) def __str__(self): return self.name
serializers.py
class VesselSerializer(serializers.ModelSerializer): class Meta: model = Vessel fields = '__all__' class ComponentSerializer(serializers.ModelSerializer): class Meta: model = Component fields = '__all__'
the view :
@api_view(['GET']) def getVessels(request): vessels = Vessel.objects.all().prefetch_related('vessel_components') vSerializer = VesselSerializer(vessels, many=True) return Response(vSerializer.data)
-
How to get top n rows in django rest framework serializers using serializers relations
I have a serializer that is working fine for all of the data, which is getting from the Database. I want to get top n numbers of rows sorted by some value.
Below is my code in views.py:
@api_view(['GET']) def org_api(request, org_id): if request.method == 'GET': try: org = Organization.objects.prefetch_related('team').get(org_id=org_id) except Organization.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializers = OrgSerializers(org) return Response(serializers.data)
And here is my serializers.py code:
class OrgSerializers(serializers.ModelSerializer): team = TeamSerializer(many=True, read_only=True) class Meta: model = Organization fields = ['org_id','name', 'team']
And here is my TeamSerializers Code:
class TeamSerializer(serializers.ModelSerializer): org_id = serializers.PrimaryKeyRelatedField(queryset=Team.objects.all()) class Meta: model = Team fields = ['name', 'resignation', 'org_id']
It is returning all of the team members of the same organization like below:
{ "org_id": "ABC", "name": "Stocks Telegraph", "team": [ { "name": "Mr. Timothy D. Cook", "title": "CEO & Director", "org_id": "ABC" }, { "name": "Mr. Luca Maestri", "title": "CFO & Sr. VP", "org_id": "ABC" }, { "name": "Mr. Jeffrey E. Williams", "title": "Chief Operating Officer", "org_id": "ABC" }, { "name": "Ms. Katherine L. Adams", "title": "Sr. VP, Gen. Counsel & Sec.", "org_id": "ABC" }, { "name": "Ms. Deirdre O'Brien", "title": "Sr. VP of People & Retail", "org_id": "ABC" }, { "name": "Mr. Chris Kondo", "title": "Sr. Director of Corp. Accounting", "org_id": "ABC" } ] }