Search code examples
pythondjangodjango-oscar

Perform CRUD operations on product class?


I'm a newbie to Django-oscar and I'm trying to develop a simple CRUD operation on Product. I've forked the catalogue app and created a views.py file

I fired the query Product.objects.create(title='Hello') and a product does get created with the following error:

AttributeError: 'NoneType' object has no attribute 'attributes'

product_title = 'MyPhone'
upc=987654321
product_class = ProductClass.objects.get_or_create(name='Phone')
def createProduct(request):
        line1
    product.name = product_title
    product.product_class = product_class
    product.upc=upc
    product.save()

When I put product=Product() in line1 I get the following error:

Cannot assign "(, False)": "Product.product_class" must be a "ProductClass" instance.

When I put product = Product.objects.create(upc=upc) I get the following error :

NoneType' object has no attribute 'attributes'

Anyone guide me on how to write a simple create operation?


Solution

  • ProductClass, Product, Category, ProductCategory = get_classes(
        'catalogue.models', ('ProductClass', 'Product', 'Category',
                             'ProductCategory'))
    create_from_breadcrumbs = get_class('catalogue.categories', 'create_from_breadcrumbs')
    
    
     def _create_item(product_class, category_str, upc, title,
                         description, stats):
            # Ignore any entries that are NULL
            if description == 'NULL':
                description = ''
    
            # Create item class and item
            product_class, __ = ProductClass.objects.get_or_create(name=product_class)
            try:
                item = Product.objects.get(upc=upc)
                stats['updated_items'] += 1
            except Product.DoesNotExist:
                item = Product()
                stats['new_items'] += 1
            item.upc = upc
            item.title = title
            item.description = description
            item.product_class = product_class
            item.save()
    
            # Category
            cat = create_from_breadcrumbs(category_str)
            ProductCategory.objects.update_or_create(product=item, category=cat)
    
            return item
    

    This is the actual way to manipulate products with provided information to the function in django oscar. For better design decisions you need to follow this convention. Modify it as you want. Let me know if you want more help. Thank you.