I am trying to insert some data into MySQL database (model LogsSeparate) through Django and Django Rest Framework but I keep getting an error which I bet is very easy to solve yet I couldn't figure it out myself:
Error:
if obj.pk is None:
AttributeError: 'LogObjTest' object has no attribute 'pk'
Code:
class LogObjTest():
def __init__(self):
self._id = None
self.bits = None
class getLogs(viewsets.ModelViewSet):
arrayTest=[]
for x in Logs.objects.all():
serializer_class = LogsSeparateSerializer
test = Fields.objects.filter(pac_id=x.message_id_decimal)
binaryTest=x.data_binary
for i in test:
obj=LogObjTest()
obj._id=x.message_id_decimal
obj.bits=binaryTest[i.fld_offset:i.fld_offset+i.fld_len]
arrayTest.append(obj)
queryset = arrayTest
LogsSeparate.objects.bulk_create(arrayTest)
print("arrayTest",arrayTest)
models.py
class LogsSeparate(models.Model):
_id = models.CharField(max_length=255, primary_key=True, null=False, db_column='_id')
bits = models.CharField(max_length=500, db_column='bits')
def __str__(self):
return self.bits```
Don't use LogObjTest. Import LogsSeparate that you created in the model.py file then use it to create a new object.
class getLogs(viewsets.ModelViewSet):
arrayTest=[]
for x in Logs.objects.all():
serializer_class = LogsSeparateSerializer
test = Fields.objects.filter(pac_id=x.message_id_decimal)
binaryTest=x.data_binary
for i in test:
obj=LogsSeparate(_id=x.message_id_decimal, bits=binaryTest[i.fld_offset:i.fld_offset+i.fld_len])
arrayTest.append(obj)
queryset = arrayTest
LogsSeparate.objects.bulk_create(arrayTest)
print("arrayTest",arrayTest)
Related
you need to get the filter using the get_related_filter class method
views
modelPath = 'Money.models'
app_model = importlib.import_module(modelPath)
cls = getattr(app_model, 'Money')
related_result = cls().get_related_filter(search_query='search_query')
models.py
class Money(models.Model):
money = models.DecimalField(max_digits=19, blank=True, default=0, decimal_places=2)
def get_related_filter(self, **kwargs):
results = super(Money, self).objects.filter(Q(money__icontains=kwargs['search_query']))
return results
def __str__(self):
return self.money
why gives 'super' object has no attribute 'objects' Python Django, and does not return filter
It makes no sense to work with super(Money, self) for two reasons:
this proxy object will resolve to Model, but Model nor it parents have an objects attribute; and
even if that was the case, you can only access .objects on a model class, not the instance.
You thus can filter with:
class Money(models.Model):
money = models.DecimalField(max_digits=19, blank=True, default=0, decimal_places=2)
def get_related_filter(self, search_query, **kwargs):
return Money.objects.filter(money__icontains=search_query)
def __str__(self):
return str(self.money)
The __str__ is also supposed to return a string, not a decimal, so you should return str(self.money), not self.money.
Environment:
Django 2.2.16
Django RESTFramework 3.8.2
Let's say, I wan to group my query_set to a specific format and serializer all models at a time.
In the past, we used a customized model to grouping the type and then feed to the customize serializer.
However, we recently trying to upgrade the Django from 1.11.x to 2.2 and so as DRF.
Then, there's an error prompt and I can't fix it. I also find a link, Look like it's a known issue in DRF.
AttributeError: 'DictField' object has no attribute 'partial'
I defined several models and serializer.
class ModelA(models.Model):
job_id = models.IntegerField()
type = models.CharField(max_length=16)
... Some fields
class ModelASerializer(serializers.ModelSerializer)
class Meta:
model = ModelA
field = '__all__'
class ModelB(models.Model):
Job_id = models.IntegerField()
type = models.CharField(max_length=16)
... Some fields
class ModelBSerializer(serializers.ModelSerializer)
class Meta:
model = ModelB
field = '__all__'
... and many models below
I create a customized model to serialize all models to specific format.
class CustomizeModel:
def __init__(self, Job_id):
self.a = {}
self.b = {}
# In below, I group the query_set by 'type'
a_set = ModelA.objects.filter(job_id=job_id)
for obj in a_set:
if obj.type not in self.a:
self.a[obj.type] = []
self.a[obj.type].append(obj)
b_set = ModelB.objects.filter(job_id=job_id)
for obj in a_set:
if obj.type not in self.b:
self.b[obj.type] = []
self.b[obj.type].append(obj)
class CustomizeSerializer(serializers.Serializer):
a = serializers.DictField(child=ModelASerializer(many=True))
b = serializers.DictField(child=ModelBSerializer(many=True))
My view:
def get_model_data(request, job_id):
...
model = CustomizeModel(job_id)
serializer = CustomizeSerializer(model)
# This serialize.data gives an error
# AttributeError: 'DictField' object has no attribute 'partial'
json_str = json.dumps(serializer.data)
return HttpResponse(json_str)
The code is worked in Django 1.11 and DRF 3.5.4
My expected result is to dump to the JSON format like below
{
a: {type1: [query_set_a filter by job_id and type1],
type2: [query_set_a filter by job_id and type2]},
b: {type1: [query_set_b filter by job_id and type1],
type2: [query_set_b filter by job_id and type2]},
}
However, I tried several ways to rewrite this serializer but got no luck.
class CustomizeModel:
def __init__(self, Job_id):
self.a = ModelA.objects.filter(job_id=job_id)
self.b = ModelB.objects.filter(job_id=job_id)
class CustomizeSerializer(serializers.Serializer):
a = ModelASerializer(many=True)
b = ModelBSerializer(many=True)
It worked. But I don't have a good approach to group_by('type') to my expected format after CustomizeSerializer.
How do I rewrite the DictField in CustomizeSerializer in Django2.2?
I got following models:
class OrderItem(models.Model):
ordered_amount = models.IntegerField(validators=[MinValueValidator(0)])
amount = models.IntegerField(default=0)
order = models.ForeignKey(
Order, on_delete=models.CASCADE, related_name="order_items"
)
class Order(models.Model):
reference = models.CharField(max_length=50)
purchase_order = models.CharField(max_length=15, blank=True, null=True)
I'm now writing a serializer for listing orders. In this OrderSerializer I need to access amount and ordered_amount in the OrderItem class. How do I do this?
This is What I have now:
class AdminOrderListSerializer(serializers.ModelSerializer):
amount = serializers.IntegerField()
ordered_amount = serializers.IntegerField()
class Meta:
model = Order
fields = [
"purchase_order",
"reference",
"amount",
"ordered_amount",
]
# noinspection PyMethodMayBeStatic
def validate_amount(self, order):
if order.order_items.amount:
return order.order_items.amount
return
# noinspection PyMethodMayBeStatic
def validate_ordered_amount(self, order):
if order.order_items.ordered_amount:
return order.order_items.ordered_amount
return
This gives me following error:
AttributeError: Got AttributeError when attempting to get a value for field amount on serializer AdminOrderItemListSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Order instance.
Original exception text was: 'Order' object has no attribute 'amount'.
There are many ways to that, one of them is SerializerMethodField:
from django.db.models import Sum
class AdminOrderListSerializer(serializers.ModelSerializer):
amount = serializers.SerializerMethodField()
ordered_amount = serializers.SerializerMethodField()
def get_amount(self,obj):
return obj.order_items.aggregate(sum=Sum('amount'))['sum']
def get_ordered_amount(self,obj):
return obj.order_items.aggregate(sum=Sum('order_amount'))['sum']
Optimized solution
Another way of achieving this is to annotate the data to queryset, and access them in serializer. For that, you need to change in view:
class SomeView(ListAPIView):
queryset = Order.objects.annotate(amount=Sum('order_items__amount'),order_amount=Sum('order_items__order_amount'))
This is a optimized solution because it reduces database hits(it only hits once).
I need to create a record with a one-to-one relationship and another field, the model of the one-to-one relationship has a filefield, when I create it, it throws me the error of the title.
This is my code.
Models
class Proyecto(models.Model):
user = models.CharField(max_length=50)
nombre_p = models.CharField(max_length=50)
descripcion_p = models.CharField(max_length=50)
file_arff = models.FileField(upload_to='arff')
def __unicode__(self):
return str(self.file_arff)
class Escenario(models.Model):
proyecto = models.ForeignKey(Proyecto)
file_txt = models.FileField(upload_to='txt/')
View
id_proyecto = Proyecto.objects.get(pk=request.session['proyecto_id'])
escenario = Escenario(proyecto=id_proyecto, file_txt=file_txt)
escenario.save()
throw me this error : AttributeError: 'file' object has no attribute '_committed'
models
class Escenario(models.Model):
proyecto = models.ForeignKey(Proyecto, related_name="xxxxx")
file_txt = models.FileField(upload_to='txt/', null=True, blank=True)
views
id_proyecto = Proyecto.objects.get(pk=request.session['proyecto_id'])
obj = Poyecto.objects.filter(id=id_proyecto)
file_txt = None #Or you can add a file here that you want to attach to the modal.
if file_txt = None:
instance = Escenario.objects.create(proyecto=obj)
else:
instance = Escenario.objects.create(proyecto=obj, file_txt=file_txt)
for x in obj:
instance.xxxxx.add(x)
I have these models:
class BlogCategory(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
def get_number_of_categorys_items(self):
return self.post_set.count()
class Post(models.Model):
title = models.CharField(max_length=130)
content = models.TextField()
category = models.ForeignKey(BlogCategory, related_name='blog_category')
def __str__(self):
return self.title
And when I try to call method get_number_of_categorys_items it cause error:
AttributeError: 'BlogCategory' object has no attribute 'post_set'
This method should return number of posts with this category.
What can I do?
Since you've specified the related_name, Django would not automatically create the related name as post_set for you. Either use:
def get_number_of_categorys_items(self):
return self.blog_category.count()
Or, don't specify the related_name:
category = models.ForeignKey(BlogCategory)