How to mutate a mobile phone number in django-graphene? - graphql

I have a customer model in django.
#models.py
class Customer(models.Model):
name = models.CharField(max_length=500, blank=True, null=True)
mobile = models.BigIntegerField(blank=True,null=True)
recent_visit_time = models.DateField(auto_now=True)
#forms.py
class CustomerForm(ModelForm):
class Meta:
model = Customer
fields = ['name','mobile']
#mutations.py
class CustomerMutation(DjangoModelFormMutation):
class Meta:
form_class = CustomerForm
I am using ModelForm to create a graphene-django mutation. I am able to add a mobile number from the admin panel, but unable to do so via a mutation. I want to add a 10 digit number but GraphQL only allows me to add 9 digit numbers.
I am getting following error:
{
"errors": [
{
"message": "Int cannot represent non 32-bit signed integer value: 88776655433"
}
],
"data": {
"customer": [
{
"id": "2",
"mobile": null,
"name": "Harsh Behl"
}
]
}
}

Related

Problems with POST on DRF

Django Rest Framework, PostgreSQL.
Models:
class Manufacturer(models.Model):
name = models.CharField(max_length=128)
class Product(models.Model):
name = models.CharField(max_length=64)
manufacturer = models.ForeignKey(
Manufacturer, on_delete=models.CASCADE, related_name="products"
)
Serializers:
class ManufacturerSerializer(serializers.ModelSerializer):
class Meta:
model = Manufacturer
fields = "__all__"
class ProductSerializer(serializers.ModelSerializer):
manufacturer = ManufacturerSerializer(read_only=True)
class Meta:
model = Product
fields = "__all__"
Then I send a GET-request, I get the following response:
{
"id": 1,
"manufacturer": {
"id": 1,
"name": "Manufacturer 1"
},
"name": "Product 1"
}
But then I send a POST-request,
{
"name": "Product 2",
"manufacturer_id": 1
}
I get the error:
null value in column "manufacturer_id" of relation "api_product" violates not-null constraint
DETAIL: Failing row contains (2, Product 2, null).
How to properly compose post-request?
For your POST send this:
{
"name": "Product 2",
"manufacturer": 1
}
You might also need to delete the whole row manufacturer = ManufacturerSerializer(read_only=True).

How can I add a field to a model serializer that has a reverse relationship with another model

I have two models. Fiction and Review model. They are the following:
class Fiction(models.Model):
"""
Model that encopasses a Movie, TV Series, book or similar
"""
MOVIE = 1
TV_SERIES = 2
BOOK = 3
PODCAST = 4
TYPE = (
(MOVIE, 'Movie'),
(TV_SERIES, 'TV-Series'),
(BOOK, 'Book'),
(PODCAST, 'Podcast')
)
title = models.CharField(max_length=50)
description = models.CharField(max_length=200)
active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
platform = models.ForeignKey(
StreamPlatform,
on_delete=models.SET_NULL,
related_name='fictions',
null = True
)
type = models.PositiveSmallIntegerField(
choices = TYPE,
default = MOVIE
)
def __str__(self):
return self.title
and
class Review(models.Model):
"""
model for fiction reviews from users
"""
rating = models.PositiveSmallIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)])
fiction = models.ForeignKey(Fiction, on_delete=models.CASCADE, related_name="reviews")
description = models.CharField(max_length=200, null = True, blank =True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.rating) + " | " + str(self.fiction)
class Meta:
ordering = ['-created']
and also two serializers
for fiction
class FictionSerializer(serializers.ModelSerializer):
"""
serializer for Movie model
"""
class Meta:
model = Fiction
fields = "__all__"
and for review
class ReviewSerializer(serializers.ModelSerializer):
class Meta:
model = Review
fields = ['rating', 'fiction', 'description']
I want to be able to display the rating of the review inside the fiction serializers. I tried something like:
rating = serializers.ReadOnlyField(source='reviews.rating')
but it didnt work. Anyone has an idea?
Since you added reviews as a related name, you can use that.
Here is a working example for you. (I've created a small project for this, so this definitely works)
class ReviewRatingSerializer(serializers.ModelSerializer):
class Meta:
model = Review
fields = ('rating', )
class FictionSerializer(serializers.ModelSerializer):
"""
serializer for Movie model
"""
reviews = ReviewRatingSerializer(many=True)
class Meta:
model = Fiction
fields = "__all__"
This might cause lots of database queries if you want to return lots of Fiction items at once.
To fix that, you should use prefetch_related in your views.py
Here is a simple example for a list view.
class GetFictionMovies(ListAPIView):
pagination_class = None
serializer_class = FictionSerializer
def get_queryset(self):
queryset = Fiction.objects.all().prefetch_related('reviews')
return queryset
Output will be similar to this.
[
{
"id": 1,
"reviews": [
{
"rating": 3
},
{
"rating": 4
}
],
"title": "Starwars",
"description": "asdasd",
"active": true,
"created": "2021-06-27T16:28:55.521748Z",
"type": 1
},
{
"id": 2,
"reviews": [
{
"rating": 5
},
{
"rating": 2
}
],
"title": "LOTR",
"description": "asdasd",
"active": true,
"created": "2021-06-27T16:29:03.227639Z",
"type": 1
},
{
"id": 3,
"reviews": [
{
"rating": 4
},
{
"rating": 3
}
],
"title": "GODFATHER",
"description": "asdasd",
"active": true,
"created": "2021-06-27T16:34:45.171444Z",
"type": 1
}
]
My advice for you is to always check for number of queries made to the db and try to avoid duplicate calls to the db.

How do you access nested object information with Django Rest Framework?

I've got two models connected through a ManyToManyField that links projects together with users, as such:
class Project(Model):
STATUS_CHOICES = (
('active', 'Active'),
('archived','Archived'),
)
name = CharField(max_length=50)
members = ManyToManyField("accounts.User", through='ProjectUser')
organization = ForeignKey(Organization, related_name="organizations", on_delete=CASCADE, verbose_name="Team")
status = CharField(max_length=10, choices=STATUS_CHOICES, default='active')
def __str__(self):
return self.name
class Meta:
db_table = 'project'
ordering = ('organization', 'name')
unique_together = ('name', 'organization',)
class ProjectUser(Model):
ROLE_CHOICES = (
('member', 'Member'),
('admin','Admin'),
)
user = ForeignKey("accounts.User", on_delete=CASCADE)
project = ForeignKey(Project, on_delete=CASCADE)
user_hour_cost = DecimalField(max_digits=6, decimal_places=2, default=0)
role = CharField(max_length=10, choices=ROLE_CHOICES, default='member')
class Meta:
db_table = 'projectuser'
ordering = ('user',)
unique_together = ('project', 'user',)
and a ProjectSerializer that looks like this:
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ["name", "organization", "members"]
I wish to extract data about the users when using the ProjectSerializer (e.g get the username, email, first name, last name from the User model). All I get back with this serializer is
{
"name": "Project X/Y",
"organization": 1,
"members": [
2,
1
]
}
Is there a way for me to traverse the information on the members so my template can use it? E.g members[0].username?
I can't just use depth = 1 because that returns data directly from User model, but ignores the fields on the ProjectUser model
I'm looking for something along the lines of
{
"name": "Project X/Y AB",
"organization": 1,
"projectusers": [
{
"user": ["id": 1, "username": "foo", "first_name": "joey"],
"project": 1,
"user_hour_cost": "550.00",
"role": "admin"
},
{
"user": ["id": 2, "username": "hellboy", "first_name": "erik"],
"project": 1,
"user_hour_cost": "190.00",
"role": "member"
}
]
}
Doesn't necessarily have to look just like this - but I need for my frontend to receive information about the user that sits on the User table in my db
Maybe you could try to specify your own serializer for the (project)users. This is covered more in depth in the official DRF docs.
class ProjectSerializer(serializers.ModelSerializer):
members = MemberSerializer(many=True)
class Meta:
model = Project
fields = ["name", "organization", "members"]
and define your Member and User Serializer:
class MemberSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = ProjectMember
fields = ["user ", "...", "role "]
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "username", "first_name", "..."]
But beware that making such a construct writeable is tricky. You would probably have to overwrite your Serializers create() methods to implement this. See here for more details.
I actually solved it by just nesting another serialized object inside ProjectUser
User Serializer
from accounts.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ("username", "first_name", "email")
and then
from .models import Project
from .models import ProjectUser
from accounts.serializers import UserSerializer
from rest_framework import serializers
class ProjectUserSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = ProjectUser
fields = ("user", "user_hour_cost", "role")
class ProjectSerializer(serializers.ModelSerializer):
projectusers = ProjectUserSerializer(many=True, read_only=True)
class Meta:
model = Project
fields = ["name", "organization", "projectusers"]
Which returned
{
"name": "Project XXAA",
"organization": 1,
"projectusers": [
{
"user": {
"username": "Google",
"first_name": "Chrome",
"email": "google#chrome.com"
},
"user_hour_cost": "550.00",
"role": "admin"
},
{
"user": {
"username": "Mozilla",
"first_name": "Joey",
"email": "mozilla#firefox.com"
},
"user_hour_cost": "190.00",
"role": "member"
}
]
}
Good enough to work with!

Get data in multiple level nested serializer using Django Rest

Need to serialize three models nested in three levels.
There are users assigned areas and these contains point. The users contains multiple areas. Areas have multiple points associated.
Users links areas using many to many relationship.
Areas Links with point using Foreign in the points.
Users can be assigned to multiple areas. Areas can have multiple points.
User Profile Model
class UserProfile(AbstractBaseUser,PermissionsMixin):
phone_number= PhoneNumberField( unique=True)
name=models.CharField(max_length=255)
organisation=models.CharField(max_length=255)
is_active=models.BooleanField(default=True)
is_staff=models.BooleanField(default=False)
added_by=models.ForeignKey(settings.AUTH_USER_MODEL,default=1)
group = models.ForeignKey('auth.Group', null=True)
areas=models.ManyToManyField('area.Area',blank=True)
objects=UserProfileManager()
Areas Model
from django.db import models
from django.conf import settings
# Create your models here.
class Area(models.Model):
areaName =models.TextField()
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL )
def __str__(self):
return self.areaName
Point Model
from django.db import models
from django.conf import settings
# Create your models here.
class Point(models.Model):
name =models.TextField()
area = models.ForeignKey('area.Area', on_delete=models.CASCADE)
latitude=models.CharField(max_length=200)
longitude=models.CharField(max_length=200)
timestamp=models.DateTimeField(auto_now=False,auto_now_add=True)
updated=models.DateTimeField(auto_now=True,auto_now_add=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL )
def __str__(self):
return self.name
I want a result like following:
{
"id": 3,
"phone_number": "+919999999999",
"name": "Ak",
"organisation": "sp",
"group": 1,
"areas": [
{
"id": 1,
"areaName": "Area 51",
"user": 1
points:[{
}]
},
{
"id": 2,
"areaName": "Rrea 343",
"user": 1
point:[{}]
}
]
},
{
"id": 4,
"phone_number": "+918888888888",
"name": "Chitra Sahu",
"organisation": "sd",
"group": 2,
"areas": [
{
"id": 1,
"areaName": "Area 51",
"user": 1
point:[{
latitude:'23.2323',
longitude:'23.2323'
},
{
latitude:'21.1223',
longitude:'32.34345'
}
]
},
{
"id": 2,
"areaName": "Rrea 343",
"user": 1
point:[{
latitude:'23.2323',
longitude:'23.2323'
},
{
latitude:'21.1223',
longitude:'32.34345'
}]
}
]
},
So Far I have tried the following
class AreasSerializer(serializers.ModelSerializer):
class Meta:
model=Area
fields=('id','areaName','user')
class AreasUserSerializer(serializers.ModelSerializer):
areas = AreasSerializer(many=True, read_only=True)
class Meta:
model = UserProfile
fields = ('id','phone_number','name','organisation','group','areas')
class AreasUserPointSerializer(serializers.ModelSerializer):
areasUsers=AreasUserSerializer()
class Meta:
model=Point
fields =('id','areasUsers' )
Views
'''Fetch list all question '''
class AreasPointsUsersListApiView(ListAPIView):
serializer_class=serializers.AreasUserPointSerializer
def get_queryset(self):
queryset=UserProfile.objects.all()
user=self.request.query_params.get('user_id',None)
if user is not None:
queryset = queryset.filter(id=user)
#if areas is not None:
# queryset = queryset.filter(areas=areas)
return queryset
.py
This code is not working properly.
I need to serialize it so that the Users consists Areas based on Many to Many relationship. These areas are linked to point using the foreign key in Point.
EDIT
Edit:
Areas serializer
I have resolved this using LocationSerializer which invoked by AreasSerializer.
I am sharing the code snippet. It was pretty easy.
class PointSerializer(serializers.ModelSerializer):
class Meta:
model = Point
fields=('id','latitude','longitude')
class AreasLocationSerializer(serializers.ModelSerializer):
points = PointSerializer(many =True, read_only=True)
class Meta:
model=Area
fields=('id','areaName','points','user')
class AreasUserLocationSerializer(serializers.ModelSerializer):
areas =AreasLocationSerializer(many=True, read_only=True)
class Meta:
model=UserProfile
fields =('id','phone_number','name','areas')

Nested Image Field in custom Page representation wagtail api

We are building a headless CMS with the wagtail API.
Our main model became very long, to make the representation cleaner and more easily accessible for the Frontend,
I am trying to group the different fields of my PageModel into sections.
But I don't manage to serialize the nested ImageField.
This is my PageModel:
class LandingPage(Page):
…
introduction_headline= models.CharField()
introduction_text = RichTextField()
introduction_icon = models.ForeignKey(
'main.CaptionImage',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name = '+',
)
…
I would like to group those fields into one section in the api, like so:
{
"id": 3,
"meta": {…},
"introduction_section": {
"introduction_headline": "intro head",
"introduction_text": "<p>intro text</p>",
"introduction_image": {
"id": 1,
"meta": {
"type": "main.CaptionImage",
"detail_url": "http://localhost/api/v2/images/1/",
"download_url": "/media/original_images/1.png"
},
"title": "german_design_image.png",
"caption": "Pretty Image"
},
},…
I managed to accomplish this in parts by writing a custom IntroductionSection - serializer:
class LandingPage(Page):
…
api_fields = [
APIField('introduction_section', serializer=IntroductionSectionField(source='*')),
…
]
class IntroductionSectionField(Field):
read_only = True
write_only = False
def to_representation(self, value):
return {
"introduction_headline" : value.introduction_headline,
"introduction_text" : value.introduction_text,
"introduction_image" : ?
}
But I simply can't figure out how to serialize the nested Image Field?
I want the same representation as the standard nested-relation-representation of the page model.
I tried around with get_related_field() method of the PageModel, tried to call the ImageSerializer, and all sorts of other things.

Resources