in server/store/management/commands/create_new_product.py [0:0]
def handle(self, *args, **options):
name = options["name"]
# nicely handle uniqueness constraints
product, created = Product.objects.get_or_create(
name=name,
defaults={
"description": options["description"],
"price": options["price"],
"active": True,
"discount_percent": options["discount_percent"],
"inventory_count": options["inventory_count"],
},
)
if created:
# Deactivate any existing active products, except for this one.
Product.objects.filter(active=True).exclude(name=name).update(active=False)
if options["image"]:
image = open(options["image"], "rb")
file_ext = pathlib.Path(options["image"]).suffix
product.image.save(str(product.id) + "_image" + file_ext, image)
self.stdout.write(f"Created product '{name}'")
# Generate testimonials
if options["testimonials"] > 0:
call_command(
"generate_testimonials",
product=product.id,
count=options["testimonials"],
)
else:
self.stdout.write(f"Product '{name}' already exists.")