i'm trying to add ticker values to a currency object using a custom command, but i can't seem to be able to add the ticker to the CurrencyTickerSerializer? i get following error TypeError: 'QuerySet' object does not support item assignment. I run this command in a specific interval that is suppose to add the ticker into the specific currency, but i guess i need to add something in order to being able to add the ticker into TickerSerializer?
Command
class Command(BaseCommand):
def handle(self, *args, **options):
comparison='DKK'
url = 'URL'
page = requests.get(url)
data = page.json()
response_data = {}
for ticker in data:
currency = Currency.objects.filter(symbol=ticker['symbol'], is_active=True)
if currency.exists():
currency['tickers'] = ticker
serializer = CurrencyTickerSerializer(data=currency)
if serializer.is_valid():
serializer.save()
serializers
class TickerSerializer(serializers.HyperlinkedModelSerializer):
currency = serializers.PrimaryKeyRelatedField(many=False, queryset=Currency.objects.all())
class Meta:
model = Ticker
fields = ('currency', 'rank', 'price_dkk', 'market_cap_dkk', 'percent_change_1h', 'percent_change_24h', 'percent_change_7d',)
class CurrencyTickerSerializer(serializers.HyperlinkedModelSerializer):
tickers = TickerSerializer(many=True)
class Meta:
model = Currency
fields = ('id', 'name','symbol', 'tickers', )
Models
class Ticker(models.Model):
rank = models.IntegerField()
price_dkk = models.DecimalField(max_digits=20, decimal_places=6)
market_cap_dkk = models.BigIntegerField()
percent_change_1h = models.DecimalField(max_digits=4, decimal_places=2)
percent_change_24h = models.DecimalField(max_digits=4, decimal_places=2)
percent_change_7d = models.DecimalField(max_digits=4, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = _('Ticker')
def __str__(self):
return self.id
class Currency(models.Model):
symbol = models.CharField(max_length=4, default='BTC', unique=True)
name = models.CharField(max_length=20, default='Bitcoin', unique=True)
img = models.ImageField(upload_to = 'static/img/currencies', blank=True)
is_active = models.BooleanField(default=False)
tickers = models.ManyToManyField(Ticker)
class Meta:
verbose_name_plural = 'currencies'
def __str__(self):
return self.name
let review your code where is this problem .
class Command(BaseCommand):
def handle(self, *args, **options):
comparison='DKK'
url = 'URL'
page = requests.get(url)
data = page.json()
response_data = {}
for ticker in data:
currency = Currency.objects.filter(symbol=ticker['symbol'], is_active=True)
if currency.exists():
currency['tickers'] = ticker
serializer = CurrencyTickerSerializer(data=currency)
if serializer.is_valid():
serializer.save()
your code is working until currency['tickers'] = ticker you treat a class as array.use currency.tickers.add(ticker) instate . it will work but not in your case because add function will complain about argument . it's need a instance Ticker class not json data . so know
for ticker in data:
currency = Currency.objects.filter(symbol=ticker['symbol'], is_active=True)
if currency.exists():
tickers = Ticker(...)
currency.tickers.add(tickers)
serializer = CurrencyTickerSerializer(data=currency)
Related
I tried to make method(location_item) that shows item by region.
And I want to implement the 'gu, dong' field(in location model) with multiple choices.
so, wrote this method code. but filtering doesn't work..
This shows all item objects, not just the objects I want.
TypeError: Field 'id' expected a number but got <Item: 애니원모어 원피스입니다!>.
[13/Aug/2022 15:01:07] "GET /item_post/location/location_item/ HTTP/1.1" 500 152955
I don't know what sholud i do.
please help me...
models.py
class Item(models.Model):
user_id = models.ForeignKey(User, related_name='item_sets', on_delete=models.CASCADE)
category_id = models.ForeignKey(Category, related_name='item_sets', on_delete=models.DO_NOTHING)
description = models.TextField()
feature = models.TextField()
product_defect = models.TextField()
size = models.CharField(max_length=6)
wear_count = models.IntegerField()
price = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.description
class Location(models.Model):
city = models.CharField(max_length=10)
gu = models.CharField(max_length=10)
dong = models.CharField(max_length=10)
def __str__(self):
return self.city+" "+self.gu+" "+self.dong
class LocationSet(models.Model):
item_id = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='location_sets')
location_id = models.ForeignKey(Location, on_delete=models.CASCADE, related_name='location_sets')
serializers.py
class ItemSerializer(serializers.ModelSerializer):
photos = PhotoSerializer(source='photo_sets', many=True, read_only=True)
style_photos = StylePhotoSerializer(source='style_photo_sets', many=True, read_only=True)
class Meta:
model = Item
fields = '__all__'
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = '__all__'
class LocationSetSerializer(serializers.ModelSerializer):
class Meta:
model = LocationSet
fields = '__all__'
views.py
class ItemViewSet(ModelViewSet):
queryset = Item.objects.all()
serializer_class = ItemSerializer
filter_backends = [SearchFilter, OrderingFilter]
search_fields = ['description'] # ?search=
ordering_fields = ['-created_at'] # ?ordering=
ordering = ['-created_at']
# here
#action(detail=False, methods=['GET'])
def location_item(self, request):
locations = Location.objects.all()
city = request.GET.get('city', None)
gu = request.GET.getlist('gu', None) # multiple choices
dong = request.GET.getlist('dong', None) # multiple choices
print(city, " ", gu, " ", dong) # > None [] [] (upper codes not work..)
if city:
locations = locations.filter(city=city)
if gu:
locations = locations.filter(gu__in=gu).distinct()
if dong:
locations = locations.filter(dong__in=dong).distinct()
location_ids = []
for i in locations:
location_ids.append(i.id)
locationsets = LocationSet.objects.filter(location_id__in=location_ids)
item_ids = []
for i in locationsets:
item_ids.append(i.item_id)
serializer = self.get_serializer(item_ids, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
To create method that shows items by region.
what sholud i do?
I think the last lines of code are wrong.
...
#action(detail=False, methods=['GET'])
def location_item(self, request):
...
# here I changed the last four lines
item_ids = [x.item_id for x in locationsets]
serializer = self.get_serializer(item_id__id__in = item_ids, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
I am doing CRUD data which has foreign keys and serializers(since I am told to use serializers instead of Forms),even though I have put the correct model and it's names in the product_edit page, the data is showing blank instead of thier saved data ,the wrong sub_category name is coming,this is how the edit page currently looks
serializer:
class CategoriesSerializer(serializers.ModelSerializer):
class Meta:
model = Categories
fields = "__all__"
extra_kwargs = {'category_name': {'required': False}}
class ColorsSerializer(serializers.ModelSerializer):
class Meta:
model = Colors
fields = "__all__"
class POLLSerializer(serializers.ModelSerializer):
# categories = serializers.StringRelatedField(many=False)
# sub_categories = serializers.StringRelatedField(many=False)
# color = serializers.StringRelatedField(many=False)
# size = serializers.StringRelatedField(many=False)
class Meta:
model = Products
fields = "__all__"
class SizeSerializer(serializers.ModelSerializer):
class Meta:
model = Size
fields = "__all__"
class SUBCategoriesSerializer(serializers.ModelSerializer):
class Meta:
model = SUBCategories
fields = "__all__"
below are the models of my CRUD
class Products(models.Model):
categories = models.ForeignKey(Categories,on_delete=models.CASCADE)
sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE)
color = models.ForeignKey(Colors,on_delete=models.CASCADE)
size = models.ForeignKey(Size,on_delete=models.CASCADE)
# image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True)
title = models.CharField(max_length=50)
price = models.CharField(max_length=10)
sku_number = models.CharField(max_length=10)
product_details = models.CharField(max_length=300)
quantity = models.IntegerField(default=0)
isactive = models.BooleanField(default=True)
class Categories(models.Model):
#made changes to category_name for null and blank
category_name = models.CharField(max_length=20)
category_description = models.CharField(max_length=20)
isactive = models.BooleanField(default=True)
def __str__(self):
return self.category_name
class Colors(models.Model):
color_name = models.CharField(max_length=10)
color_description = models.CharField(max_length=10)
isactive = models.BooleanField(default=True)
def __str__(self):
return self.color_name
class Size(models.Model):
size_name = models.CharField(max_length=10)
size_description = models.CharField(max_length=20)
isactive = models.BooleanField(default=True)
def __str__(self):
return self.size_name
class SUBCategories(models.Model):
category_name = models.ForeignKey(Categories, on_delete=models.CASCADE)
sub_categories_name = models.CharField(max_length=20)
sub_categories_description = models.CharField(max_length=20)
isactive = models.BooleanField(default=True)
def __str__(self):
return self.sub_categories_name
update function
def update(request,id):
if request.method == 'GET':
print('GET',id)
edit_products = SUBCategories.objects.filter(id=id).first()
s= SUBCategoriesSerializer(edit_products)
category_dict = Categories.objects.filter(isactive=True)
category = CategoriesSerializer(category_dict, many=True)
sub_category_dict = SUBCategories.objects.filter(isactive=True)
sub_category = SUBCategoriesSerializer(sub_category_dict,many=True)
color_dict = Colors.objects.filter(isactive=True)
color = ColorsSerializer(color_dict,many=True)
size_dict = Size.objects.filter(isactive=True)
size = SizeSerializer(size_dict,many=True)
hm = {"context": category.data,"sub_context":sub_category.data,"color_context":color.data,"size_context":size.data,"SUBCategories":s.data}
return render(request,'polls/product_edit.html',hm)
else:
print('POST',id)
editproducts = {}
d = Products.objects.filter(id=id).first()
if d:
editproducts['categories']=request.POST.get('categories')
editproducts['sub_categories']=request.POST.get('sub_categories')
editproducts['color']=request.POST.get('color')
editproducts['size']=request.POST.get('size')
editproducts['title']=request.POST.get('title')
editproducts['price']=request.POST.get('price')
editproducts['sku_number']=request.POST.get('sku_number')
editproducts['product_details']=request.POST.get('product_details')
# print(editsubcategories)
form = SUBCategoriesSerializer(d,data= editproducts)
if form.is_valid():
form.save()
print("form data",form.data)
print('form error',form.errors)
messages.success(request,'Record Updated Successfully...!:)')
return redirect('polls:show')
else:
print(form.errors)
return redirect("polls:show")
where am I going wrong in the code?
you must create product serializer like below
class ProductSerial(ModelSerializer):
class Meta:
model = Products
fields = '__all__'
and pass editproducts to this serializer
and also you have to be careful that pass id's of
categories
sub_categories
color
size
into request.POST data
I'm working with a ManyToManyField and using a ModelMultipleChoice on form, I want to get the entries, but all I get is appname.Extra.none
models.py
class Extra(models.Model):
extra_n = models.CharField(max_length=200)
extra_price = models.IntegerField(default=0)
def __str__(self):
return self.extra_n
class Meal(models.Model):
restaurant = models.ForeignKey(Restaurant, on_delete=models.PROTECT)
category = models.ForeignKey(MealCategory, on_delete=models.PROTECT)
name = models.CharField(max_length=500)
short_description = models.CharField(max_length=500)
image = models.ImageField(upload_to='meal_images/', blank=False)
price = models.IntegerField(default=0)
extras = models.ManyToManyField(Extra, related_name='extras')
def __str__(self):
return self.name
forms.py
class MealForm(forms.ModelForm):
extras = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Meal.extras)
class Meta:
model = Meal
exclude = ("restaurant",)
views.py
def restaurant_meal(request):
meals = Meal.objects.filter(restaurant = request.user.restaurant).order_by("-id")
return render(request, 'restaurant/meal.html', {"meals": meals})
The output desired is getting the extras added displayed on restaurant_meal view.
you can try change
meals = Meal.objects.filter(restaurant = request.user.restaurant).order_by("-id")
to
meals = Meal.objects.filter(restaurant = request.user.restaurant).prefetch_related('extras').order_by("-id")
and try again.
Doc of this in prefetch_related
I have to serialize data for a django rest framework application, some of values will be on Brazilian currency format like 1.234,45.
How can I bind those number to work with django rest serializer and django models
My model:
class Produto(models.Model):
prod_codigo = models.AutoField(db_column='prod_codigo', primary_key=True)
prod_alias = models.CharField(db_column='prod_alias', max_length=50, null=False)
prod_descricao = models.CharField(db_column='prod_descricao', max_length=255, null=False)
prod_valor_venda = models.DecimalField(db_column='prod_valor_venda', max_digits=13, decimal_places=2)
prod_valor_compra = models.DecimalField(db_column='prod_valor_compra', max_digits=13, decimal_places=2)
prod_peso_b = models.DecimalField(db_column='prod_peso_b', max_digits=13, decimal_places=2)
prod_peso_l = models.DecimalField(db_column='prod_peso_l', max_digits=13, decimal_places=2)
My serializer:
class ProdutoSerializer(serializers.Serializer):
prod_codigo = serializers.IntegerField(read_only=True)
prod_alias = serializers.CharField(required=False, allow_blank=True)
prod_descricao = serializers.CharField(required=True, allow_blank=True)
prod_valor_venda = serializers.DecimalField(max_digits=13, decimal_places=2)
prod_valor_compra = serializers.DecimalField(max_digits=13, decimal_places=2)
prod_peso_b = serializers.DecimalField(max_digits=13, decimal_places=2)
prod_peso_l = serializers.DecimalField(max_digits=13, decimal_places=2)
class Meta:
model = Produto
def create(self, validated_data):
return Produto.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.prod_codigo = validated_data.get('prod_codigo', instance.prod_codigo)
instance.prod_alias = validated_data.get('prod_alias', instance.prod_alias)
instance.prod_descricao = validated_data.get('prod_descricao', instance.prod_descricao)
instance.prod_valor_venda = validated_data.get('prod_valor_venda', instance.prod_valor_venda)
instance.prod_valor_compra = validated_data.get('prod_valor_compra', instance.prod_valor_compra)
instance.prod_peso_b = validated_data.get('prod_peso_b', instance.prod_peso_b)
instance.prod_peso_l = validated_data.get('prod_peso_l', instance.prod_peso_l)
instance.prod_peso_q = validated_data.get('prod_peso_q', instance.prod_peso_q)
instance.save()
return instance
If I understand it correctly and 1.234,45 equals to 1.23445 why not handle this on the client side? In my opinion this is the best way to handle to handle format issues.
If you still wanna do it in your backend app you can override to_representation(self, instance)
or use SerializerMethodField like the code below:
class ProdutuSerializer(serializer.ModelSerializer):
...
your_field = serializers.SerializerMethodField()
def get_your_field_name(self, instance):
""" stringify your field """
return "some format" % instance.field
Hope that it helps!
I'm using Marshmallow's nested serializers and getting the error "KeyError: u'manager'".
Here are my serializers:
class ShiftSerializer(Schema):
agent = fields.String()
date = fields.String()
end = fields.String()
status = fields.String()
class KPIShiftSerializer(Schema):
interval = fields.DateTime()
incoming = fields.Integer()
duration = fields.Decimal()
shifts_future = fields.Nested(ShiftSerializer, many=True)
shifts_current = fields.Nested(ShiftSerializer, many=True)
shifts_ending = fields.Nested(ShiftSerializer, many=True)
And my models:
class Shift(models.Model):
agent = models.CharField(default=" ", max_length=200)
date = models.CharField(default='01/01/1900', max_length=10)
end = models.DateTimeField(default=utc.localize(datetime(1900,1,1)))
status = models.CharField(default='Available', max_length=200)
class KPI(models.Model):
interval = models.DateTimeField(default=timezone.now)
incoming = models.IntegerField(default=0)
duration = models.FloatField(default=0)
shifts_future = models.ManyToManyField(Shift, related_name="returning")
shifts_current = models.ManyToManyField(Shift, related_name="staffed")
shifts_ending = models.ManyToManyField(Shift, related_name="leaving")