operator does not exist: bigint = uuid in django - python

I want to use uuid field as my id (primary key) but there is something wrong with it and i can't fix it
this is my model
class Cart(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
created_at = models.DateTimeField(auto_now_add=True)
class CartItem(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE , related_name='items')
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.PositiveSmallIntegerField()
class Meta:
unique_together = [['cart'], ['product']]
This Is MY Serializer.py
class CartItemSerializer(serializers.ModelSerializer):
class Meta:
model = Cart
fields = ['id', 'product', 'quantity']
class CartSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(read_only=True)
items = CartItemSerializer(many=True)
class Meta:
model = Cart
fields = ['id', 'items']
And My Views.py is
class CartViewSet(CreateModelMixin, RetrieveModelMixin, GenericViewSet):
queryset = Cart.objects.prefetch_related('items__product').all()
serializer_class = CartSerializer
My database Is postgres Sql
My Error when I browse my api my guid

Make sure that you create a UUID field uuid = UUIDField(primary_key=True, default=None, editable=False) first before your initial migration.
If you have already done the initial migration, then drop the database and recreate it and don't forget to delete the migration files.
Run migrations again and you should be good to go.

Related

How to force fill field to Inline Models in Django

We added the model named Comment as inlines in the Course model. We want to make it mandatory to fill in the fields in the Inlines model when the Save button is clicked.
# models.py
class Course(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
...
updated_at = models.DateTimeField(auto_now=True))
class Comment(models.Model):
CHOICES=[(1,'Approved'),
(0,'Rejected')]
course = models.ForeignKey(Course, on_delete=models.PROTECT)
opinion = models.IntegerField(choices=CHOICES)
comment = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# admin.py
class CommentInline(admin.StackedInline):
model = Comment
max_num = 1
radio_fields={'opinion':admin.HORIZONTAL}
#admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
list_display = ('title', 'category', 'reviewer', 'created_at',)
inlines = [CommentInline,]

How do you add validation to django rest framework api

I have two models, which look like this:
class Item(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60)
sku = models.CharField(max_length=60)
description = models.TextField()
price = models.DecimalField(max_digits=6, decimal_places=2)
location = models.CharField(max_length=60)
serial_number = models.CharField(max_length=60)
def __str__(self):
return self.name
class Warehouse(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60)
def __str__(self):
return self.name
and they have two serializers which look like this:
class ItemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Item
fields = ('id', 'name', 'sku', 'description', 'price', 'location', 'serial_number')
#we need a validator that checks if location is in the list of warehouses
#we need a validator that checks if sku is in the list of products
class WarehouseSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Warehouse
fields = ('id', 'name')
I need a way to ensure that the location field for newly created items matches an existing name field from a warehouse. I also need the deletion of a warehouse to trigger the deletion of all items in that warehouse, or, failing that; if the warehouse has items, it cannot be deleted.
I'm brand new to python and django, so any help would be massively appreciated!
for reference, my views class looks like
class ItemViewSet(viewsets.ModelViewSet):
queryset = Item.objects.all().order_by('name')
serializer_class = ItemSerializer
class WarehouseViewSet(viewsets.ModelViewSet):
queryset = Warehouse.objects.all().order_by('name')
serializer_class = WarehouseSerializer
if that helps, but from what I can see I don't expect it to.
Thanks in advance!
I think the problem here is your data models. It's clear that a warehouse and an item have a one to many relationship. With that, you would have something like this in your models.
from django.db import models
class Warehouse(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60)
def __str__(self):
return self.name
class Item(models.Model):
id = models.AutoField(primary_key=True)
warehouse = models.ForeignKey(Warehouse, related_name="items", on_delete=models.CASCADE)
name = models.CharField(max_length=60)
sku = models.CharField(max_length=60)
description = models.TextField()
price = models.DecimalField(max_digits=6, decimal_places=2)
location = models.CharField(max_length=60)
serial_number = models.CharField(max_length=60)
def __str__(self):
return self.name
The on_delete=models.CASCADE will ensure that all items related to a warehouse are deleted when a warehouse is deleted. The foreign key relationship will ensure that warehouse id you provide when creating the item, exists before the item is created.
The other files will look as follows.
serializers.py
from rest_framework import serializers
from .models import Warehouse, Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('id', 'name', 'sku', 'description', 'price', 'location', 'serial_number', "warehouse")
class WarehouseSerializer(serializers.HyperlinkedModelSerializer):
items = serializers.StringRelatedField(many=True, required=False)
class Meta:
model = Warehouse
fields = ('id', 'name', 'items')
views.py
from .models import Item, Warehouse
from .serializers import ItemSerializer, WarehouseSerializer
from rest_framework import viewsets
class ItemViewSet(viewsets.ModelViewSet):
queryset = Item.objects.all().order_by('name')
serializer_class = ItemSerializer
class WarehouseViewSet(viewsets.ModelViewSet):
queryset = Warehouse.objects.all().order_by('name')
serializer_class = WarehouseSerializer

Unable to save relationship between two objects with Django Rest Framework

I am building a Django/React App to allow users to submit orders that need to go from A to B. The user initially saves the addresses in the database and then he/she selects it in the order form. When they submit I attempt to create a relationship in the database, I'm using Django Rest Framework serializers to create the Order object in the database.
Unfortunately, I'm unable to successfully save the items as I'm not properly linking the addresses to the order. Im getting the following error:
destinationAddress: ["Invalid value."]
originAddress: ["Invalid value."]
Models
class Order(models.Model):
originAddress = models.ForeignKey(Address, related_name="originAddress", null=True, on_delete=models.CASCADE)
destinationAddress = models.ForeignKey(Address, related_name="destinationAddress", null=True, on_delete=models.CASCADE)
packages = models.CharField("Packages", max_length=1024)
class Address(models.Model):
address_code = models.CharField(max_length=250)
contact = models.CharField("Contact", max_length=1024)
phone = models.CharField("Phone", max_length=20)
company = models.CharField("Company", max_length=250)
addressLine1 = models.CharField("Address line 1", max_length=1024)
addressLine2 = models.CharField("Address line 2", max_length=1024, blank=True)
postalCode = models.CharField("Postal Code", max_length=12)
city = models.CharField("City", max_length=1024)
state = models.CharField("State", max_length=250)
Serializers
class AddressSerializer(serializers.ModelSerializer):
class Meta:
model = Address
fields = '__all__'
class OrderSerializer(serializers.ModelSerializer):
originAddress = serializers.SlugRelatedField(
queryset=Address.objects.all(),
slug_field='pk'
)
destinationAddress = serializers.SlugRelatedField(
queryset=Address.objects.all(),
slug_field='pk'
)
class Meta:
model = Order
fields = ('id', 'packages', 'destinationAddress', 'originAddress')
ViewSets
class OrderViewSet(viewsets.ModelViewSet):
queryset = Order.objects.all()
permission_classes = [
permissions.AllowAny
]
serializer_class = OrderSerializer
class AddressViewSet(viewsets.ModelViewSet):
queryset = Address.objects.all()
permission_classes = [
permissions.AllowAny
]
serializer_class = AddressSerializer
Any ideas? Thanks
Solved it by replacing SlugRelatedField to PrimaryKeyRelatedField
class OrderSerializer(serializers.ModelSerializer):
originAddress = serializers.PrimaryKeyRelatedField(
queryset=Address.objects.all(), allow_null=True, required=False
)
destinationAddress = serializers.PrimaryKeyRelatedField(
queryset=Address.objects.all(), allow_null=True, required=False
)
class Meta:
model = Order
fields = ('id', 'packages', 'destinationAddress', 'originAddress')

Django postgres migrate models column discount.category_name_id does not exist

Hi i'm trying to combine Django backend and postgresql database together.
Here is my database tables:
My models.py in Django
from django.db import models
# Create your models here.
class Categories(models.Model):
id = models.IntegerField(primary_key=True)
name = models.TextField(null=True, unique=True)
class Meta:
db_table = 'categories'
def __str__(self):
return self.name
class Website(models.Model):
id = models.IntegerField(primary_key=True)
site = models.TextField(null=True, unique=True)
class Meta:
db_table= 'website'
def __str__(self):
return self.site
class Discount(models.Model):
id = models.IntegerField(primary_key=True)
product_name = models.TextField()
product_price = models.TextField()
product_old_price = models.TextField()
product_link = models.TextField()
category_name = models.ForeignKey(Categories, on_delete=models.CASCADE, null=True, to_field='name')
product_site = models.ForeignKey(Website, on_delete=models.CASCADE, null=True, to_field='site')
product_image = models.TextField()
class Meta:
db_table = 'discount'
def __str__(self):
return self.product_name
I managed to link Django and postgresql together following tutorials but when i try to migrate the database for the first time it come with this error :
column discount.category_name_id does not exist LINE 1:
..."."product_old_price", "discount"."product_link", "discount"...
^ HINT: Perhaps you meant to reference the column "discount.category_name".
i though i linked my foreign key from discount.category_name to categories.name with to_field='name' in the ForeignKeyField but somehow it used the discount.category_name_id ? i don't know where the category_name_id is, it's not in my tables
Any help would be appreciate!
Below field is not reflected in the database, please check you db fields name if not then create the one dummy migration and write the script for that
category_name = models.ForeignKey(Categories, on_delete=models.CASCADE, null=True, to_field='name')
I managed to fixed it by adding
db_column='category_name'
to the ForeignKey field
It seems that i need to specific what column that actually is a Foreign key in my Postgresql tables to the ORM
category_name = models.ForeignKey(Categories, on_delete=models.CASCADE, null=True, to_field='name', db_column='category_name')
product_site = models.ForeignKey(Website, on_delete=models.CASCADE, null=True, to_field='site', db_column='product_site')

Django Python 'Customer' object is not iterable

from django.db import models
class Customer(models.Model):
cust_firstname=models.TextField(max_length=50)
cust_lastname=models.TextField(max_length=50)
cust_company=models.TextField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
cust_contact_number = models.IntegerField()
cust_email = models.TextField(max_length=100)
cust_address=models.TextField(max_length=200,default=None)
class Employee(models.Model):
employee_firstname = models.TextField(max_length=50)
employee_lastname = models.TextField(max_length=50)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
employee_contact_number = models.IntegerField()
employee_email = models.TextField(max_length=100)
employee_designation = models.TextField(max_length=50)
employee_address=models.TextField(max_length=200, default=None)
class ProjectDetails(models.Model):
customer = models.ForeignKey(Customer)
employee=models.ForeignKey(Employee)
project_name = models.TextField(max_length=50)
project_startdate = models.DateTimeField(auto_now=False, default=None)
project_status = models.TextField(default="Initial")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
The above code is my model declaration
and my Serializer class is
from ProjectTemplate.models import Customer, Employee, ProjectDetails
from rest_framework import serializers
class CustomerSerializers(serializers.ModelSerializer):
class Meta:
model=Customer
fields = ('id','cust_firstname','cust_lastname','cust_company','created_at','updated_at','cust_contact','cust_email','cust_address')
read_only_fields = ('created_at', 'updated_at')
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model=Employee
fields = ('id','employee_firstname','employee_lastname','created_at','updated_at','employee_contact','employee_email','employee_designation','employee_address')
read_only_fields = ('created_at', 'updated_at')
class ProjectDetailsSerializer(serializers.ModelSerializer):
customer = CustomerSerializers(many=True, read_only=True)
employee = EmployeeSerializer(many=True, read_only=True)
class Meta:
model = ProjectDetails
fields = ('id','project_name','project_startdate','created_at','updated_at','project_status','customer','employee')
read_only_fields = ('created_at', 'updated_at')
In my view i have the below code
def get(self, request, format=None):
queryset = ProjectDetails.objects.all()
projectid = self.request.query_params.get('pk', None)
if projectid is not None:
queryset = queryset.get(id=projectid)
serializer = ProjectDetailsSerializer(queryset, many=False)
return Response(serializer.data)
else:
serializer = ProjectDetailsSerializer(queryset, many=True)
return Response(serializer.data)
And my URL for the above view is
url(r'^api/v1/projects/$', ProjectListView.as_view()),
And when i try to access the URL on my Browser i get TypeError. Im trying to get all the Customers and Employees who belong to a project. But it fails can any one help me to fix this.
I'm trying to get all the Customers and Employees who belong to a project.
I am not sure what do you want to achieve here because looking at your model, an instance of ProjectDetail will only have one customer and one employee:
class ProjectDetails(models.Model):
customer = models.ForeignKey(Customer)
employee=models.ForeignKey(Employee)
Considering this, using many=True doesn't make any sense in the serializer. So this is what causing the error:
class ProjectDetailsSerializer(serializers.ModelSerializer):
customer = CustomerSerializers(many=True, read_only=True)
employee = EmployeeSerializer(many=True, read_only=True)
UPDATE: To show a specific field from the related object:
Based on the comments in the answer the OP want to show the name of customer or employee instead of id.
It can be achieved using a SlugRelatedField:
class ProjectDetailsSerializer(serializers.ModelSerializer):
customer = serializers.SlugRelatedField(slug_field='cust_firstname', read_only=True)
employee = serializers.SlugRelatedField(slug_field='employee_firstname ', read_only=True)
# other fields
Do note that using SlugRelatedField you can get only one field as in the example above you would get firstname for both.

Categories