I am trying to get itemwise inventory desired result is like this
[
{
'item' : shoes,
'total_unit' : 134
},
{
'item': sneaker,
'unit': 100
}
]
but I am getting result like
[
{
"item": 5,
"unit": 134
},
{
"item": 4,
"unit": 100
}
]
I want to get item name instead of id
Models.py
class Item(models.Model):
item_name = models.CharField(max_length=50)
srn_code = models.CharField(max_length=20,unique=True)
category = models.ForeignKey(Category,related_name='categories',on_delete=models.CASCADE)
def __str__(self):
return self.item_name
class Transaction(models.Model):
category = models.ForeignKey(Category,on_delete=models.CASCADE)
item = models.ForeignKey(Item,on_delete=models.CASCADE)
size = models.CharField(blank=True,max_length=20)
unit = models.IntegerField()
unit_price = models.DecimalField(decimal_places=2,max_digits=20)
supplier = models.ForeignKey(Supplier,on_delete=models.CASCADE)
tran_date = models.DateField(auto_now=False,auto_created=False,blank=False)
created_date = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.item.item_name} {self.unit}"
serializer.py
class InventorySerializer(serializers.ModelSerializer):
item = serializers.CharField(read_only=True)
total_unit = serializers.IntegerField(read_only=True)
class Meta():
model = Transaction
fields = ['item','total_unit']
views.py
class InventoryModelViewSet(ModelViewSet):
queryset = Transaction.objects.all()
serializer_class = InventorySerializer
def get_queryset(self):
return Transaction.objects.values('item').annotate(
total_unit = Sum('unit')
).order_by('item')
Thanks for posting my question, I have sorted out my question, my solution is below, if anybody needs or gets query like this, then its might be helpful.
I have declared a method in serializers class for get item_name from another table
class InventorySerializer(serializers.ModelSerializer):
item = serializers.CharField(read_only=True)
total_unit = serializers.IntegerField(read_only=True)
item_name = serializers.SerializerMethodField()
class Meta():
model = Transaction
fields = ['item','item_name','total_unit']
def get_item_name(self, obj):
item_obj = Item.objects.filter(id=obj['item']).first()
item_name = model_to_dict(item_obj)
return item_name['item_name']
`
I created an update mutation as follows, with django==3.1.4 and graphene==2.1.8 :
# models.py
class CustomUser(AbstractUser):
# email = models.EmailField()
firebase_id = models.CharField(max_length=50, null=True)
nickname = models.CharField(max_length=50, null=True)
name = models.CharField(max_length=20, null=True)
gender = models.IntegerField(choices=Gender, default=3)
phone = models.CharField(max_length=20, null=True)
birthday = models.DateField(default=datetime(2020,1,1))
address = models.CharField(max_length=200, null=True)
profile_image = models.ImageField(default='default-avatar.png', upload_to='users/',
null=True, blank=True)
class UpdateMember(graphene.Mutation):
class Arguments:
firebase_id = graphene.String(required=True)
nickname = graphene.String()
name = graphene.String()
gender = graphene.Int()
phone = graphene.String()
birthday = graphene.Date()
address = graphene.String()
profile_image = graphene.String()
class Meta:
exclude = ["password"]
member = graphene.Field(MemberType)
success = graphene.Boolean()
# #login_required
#staticmethod
def mutate(root, info, firebase_id, **kwargs):
success = False
member_instance = CustomUser.objects.get(firebase_id=firebase_id)
if member_instance:
print(member_instance)
success = True
for k, v in kwargs.items():
member_instance.k = v
member_instance.save()
return UpdateMember(member=member_instance, success=True)
else:
return UpdateMember(member=None, success=False)
Running GQL below:
mutation {
updateMember(
firebaseId:"777",
name:"JJJJ")
{
success
}
}
Response:
{
"data": {
"updateMember": {
"success": true
}
}
}
But I checked the database, it seems no change in it, I think .save() should have done the work persisting changes to database......
Creating Member works fine. Using PostgresQL
Could anyone figure out why?
There is several issues in your code:
You can not assign your model fields using string like that. See this thread
for k, v in kwargs.items():
member_instance.k = v
member_instance.save()
Currently your member_instance.k has nothing to do with variable k inside for loop.
firebase_id field should be unique.
Currently you call CustomUser.objects.get(firebase_id=firebase_id) which is risky because firebase_id is not unique field. This may lead Multiple objects error if you have more than one CustomUsers saved with same id. To fix it, just define:
class CustomUser(AbstractUser):
# email = models.EmailField()
firebase_id = models.CharField(max_length=50, unique=True)
...
To check if your member_instance has really updated. You can for example print out the values before saving it and run some test cases before final implementation. For example:
if member_instance:
print(member_instance)
success = True
for k, v in kwargs.items():
member_instance.k = v
print(member_instance.k)
print(k)
print(getattr(member_instance, k))
member_instance.save()
Problem:
I want to update a foreign key field and I can not find my mistake why my changes to that fields are not saved. I want to be able to update clan and wingman.
serializer.py
class UpdateProfileInfoSerializer(serializers.Serializer):
id = serializers.CharField(required=True)
wingmanId = serializers.IntegerField(required=False)
clanId = serializers.IntegerField(required=False)
image = serializers.ImageField(required=False)
titleImage = serializers.ImageField(required=False)
description = serializers.CharField(required=False)
class Meta:
model = ProfileInfo
fields = ['id', 'clanId', 'description', 'image', 'titleImage', 'wingmanId']
def update(self, instance, validated_data):
clan_id = validated_data.get('clanId')
wingman_id = validated_data.get('wingmanId')
if clan_id:
if instance.clan:
instance.clan.id = clan_id
if wingman_id:
if instance.wingman:
instance.wingman.id = wingman_id
instance.image = validated_data.get('image', instance.image)
instance.titleImage = validated_data.get('titleImage', instance.titleImage)
instance.description = validated_data.get('description', instance.description)
instance.save()
return instance
Thank you for your help. I think I am doing something fundamentally wrong.
Try this please, I think it is better.
class UpdateProfileInfoSerializer(serializers.Serializer):
id = serializers.CharField(required=True)
wingmanId = serializers.IntegerField(required=False)
clanId = serializers.IntegerField(required=False)
image = serializers.ImageField(required=False)
titleImage = serializers.ImageField(required=False)
description = serializers.CharField(required=False)
class Meta:
model = ProfileInfo
fields = ['id', 'clanId', 'description', 'image', 'titleImage', 'wingmanId']
def update(self, instance, validated_data):
clan_id = validated_data.get('clanId')
wingman_id = validated_data.get('wingmanId')
if clan_id:
if instance.clan:
try:
clan_obj = Clan.objects.get(id=clan_id)
instance.clan = clan_obj
except:
pass
if wingman_id:
if instance.wingman:
try:
wingman_obj = Wingman.objects.get(id=wingman_id)
instance.wingman = wingman_obj
except:
pass
instance.image = validated_data.get('image', instance.image)
instance.titleImage = validated_data.get('titleImage', instance.titleImage)
instance.description = validated_data.get('description', instance.description)
instance.save()
return instance
New to JSON/RUBY.
I have a Rest Service returning a JSON string and I would like to parse this into a Ruby Class. Is this recommended? I have tried the following example and get error- Can't convert String to Integer. This is for a rhomobile app I'm working on. I'm thinking POJO-->JSON-->Ruby. Any advice would be appreciated.
Ruby
##get_result = #params['body']
puts "##get_result : #{##get_result}"
data2 =##get_result
cust1 = data2["PolicyList"].map { |rd| PolicyList.new(rd["policyNbr"], rd["systemId"], rd["insuredName"],
rd["type"], rd["statusCd"], rd["statusDes"], rd["payorZipcode"],
rd["lastPaymentDate"], rd[lastPaymentAmount], rd["pastDueDate"], rd["pastDueAmount"],
rd["currentDueDate"], rd["currentDueAmount"], rd["eft"],
rd["suspenseAmt"], rd["expireTime"]) }
Class
class PolicyList
attr_accessor :policyNbr, :systemId, :insuredName,
:type, :statusCd, :statusDes, :payorZipcode,
:lastPaymentDate,:lastPaymentAmount,:pastDueDate,
:pastDueAmount,:currentDueDate,:currentDueAmount,:eft,
:suspenseAmt,:expireTime
def initialize(policyNbr, systemId,insuredName,type,statusCd,statusDes,payorZipcode,lastPaymentDate,lastPaymentAmount,
pastDueDate,pastDueAmount,currentDueDate,currentDueAmount,eft,suspenseAmt,expireTime)
#systemId = systemId
#insuredName = insuredName
#type = type
#statusCd = statusCd
#statusDes = statusDes
#payorZipcode = payorZipcode
#lastPaymentDate = lastPaymentDate
#lastPaymentAmount = lastPaymentAmount
#pastDueDate = pastDueDate
#pastDueAmount = pastDueAmount
#currentDueDate = currentDueDate
#currentDueAmount = currentDueAmount
#eft = eft
#suspenseAmt = suspenseAmt
#expireTime = expireTime
end
end
Returned JSON
[{"policyNbr":"0000001","systemId":"MB","insuredName":"JOHN DOE ","type":"MEMBERSHIP","statusCd":"01","statusDes":"PAID","payorZipcode":"99999","lastPaymentDate":"07/12/2012","lastPaymentAmount":25.00,"pastDueDate":"","pastDueAmount":0.00,"currentDueDate":"","currentDueAmount":0.00,"eft":false,"suspenseAmt":false,"expireTime":1362152384971},{"policyNbr":"0000002","systemId":"PC","insuredName":"JOHN DOE","type":"AUTO","statusCd":"01","statusDes":"PAID","payorZipcode":"99999","lastPaymentDate":"02/15/2013","lastPaymentAmount":308.50,"pastDueDate":"","pastDueAmount":0.00,"currentDueDate":"","currentDueAmount":0.00,"eft":false,"suspenseAmt":false,"expireTime":0},{"policyNbr":"0000003","systemId":"PC","insuredName":"JOHN DOE","type":"HOME","statusCd":"01","statusDes":"PAID","payorZipcode":"99999","lastPaymentDate":"09/05/2012","lastPaymentAmount":149.00,"pastDueDate":"","pastDueAmount":0.00,"currentDueDate":"","currentDueAmount":0.00,"eft":false,"suspenseAmt":false,"expireTime":0}]
You're getting an array of PolicyList objects, but there is no key called 'PolicyList'. I think you need this:
cust1 = data2.map { |rd| PolicyList.new(rd["policyNbr"], rd["systemId"], rd["insuredName"],
rd["type"], rd["statusCd"], rd["statusDes"], rd["payorZipcode"],
rd["lastPaymentDate"], rd['lastPaymentAmount'], rd["pastDueDate"], rd["pastDueAmount"],
rd["currentDueDate"], rd["currentDueAmount"], rd["eft"],
rd["suspenseAmt"], rd["expireTime"]) }
To make it easier for you. Here is a complete example.
class PolicyList
attr_accessor :policyNbr, :systemId, :insuredName,
:type, :statusCd, :statusDes, :payorZipcode,
:lastPaymentDate,:lastPaymentAmount,:pastDueDate,
:pastDueAmount,:currentDueDate,:currentDueAmount,:eft,
:suspenseAmt,:expireTime
def initialize(policyNbr, systemId,insuredName,type,statusCd,statusDes,payorZipcode,lastPaymentDate,lastPaymentAmount,
pastDueDate,pastDueAmount,currentDueDate,currentDueAmount,eft,suspenseAmt,expireTime)
#systemId = systemId
#insuredName = insuredName
#type = type
#statusCd = statusCd
#statusDes = statusDes
#payorZipcode = payorZipcode
#lastPaymentDate = lastPaymentDate
#lastPaymentAmount = lastPaymentAmount
#pastDueDate = pastDueDate
#pastDueAmount = pastDueAmount
#currentDueDate = currentDueDate
#currentDueAmount = currentDueAmount
#eft = eft
#suspenseAmt = suspenseAmt
#expireTime = expireTime
end
end
require 'json'
json = <<-JSON
[{"policyNbr":"0000001","systemId":"MB","insuredName":"JOHN DOE ","type":"MEMBERSHIP","statusCd":"01","statusDes":"PAID","payorZipcode":"99999","lastPaymentDate":"07/12/2012","lastPaymentAmount":25.00,"pastDueDate":"","pastDueAmount":0.00,"currentDueDate":"","currentDueAmount":0.00,"eft":false,"suspenseAmt":false,"expireTime":1362152384971},{"policyNbr":"0000002","systemId":"PC","insuredName":"JOHN DOE","type":"AUTO","statusCd":"01","statusDes":"PAID","payorZipcode":"99999","lastPaymentDate":"02/15/2013","lastPaymentAmount":308.50,"pastDueDate":"","pastDueAmount":0.00,"currentDueDate":"","currentDueAmount":0.00,"eft":false,"suspenseAmt":false,"expireTime":0},{"policyNbr":"0000003","systemId":"PC","insuredName":"JOHN DOE","type":"HOME","statusCd":"01","statusDes":"PAID","payorZipcode":"99999","lastPaymentDate":"09/05/2012","lastPaymentAmount":149.00,"pastDueDate":"","pastDueAmount":0.00,"currentDueDate":"","currentDueAmount":0.00,"eft":false,"suspenseAmt":false,"expireTime":0}]
JSON
##get_result = JSON.parse(json)
puts "##get_result : #{##get_result}\n\n"
data2 =##get_result
cust1 = data2.map { |rd| PolicyList.new(rd["policyNbr"], rd["systemId"], rd["insuredName"],
rd["type"], rd["statusCd"], rd["statusDes"], rd["payorZipcode"],
rd["lastPaymentDate"], rd['lastPaymentAmount'], rd["pastDueDate"], rd["pastDueAmount"],
rd["currentDueDate"], rd["currentDueAmount"], rd["eft"],
rd["suspenseAmt"], rd["expireTime"]) }
puts cust1.inspect