所以我有模型GeneralUser
,Business
,Brand
,Bottle
。
class Business(models.Model):
name = models.CharField(max_length=100, blank=False)
owner = models.ForeignKey(GeneralUser, on_delete=models.CASCADE, blank=False, related_name="businesses")
class Brand(models.Model):
name = models.CharField(max_length=150, blank=False, unique=True)
businesses = models.ManyToManyField(Business, related_name="brands", blank=False)
class Bottle(models.Model):
name = models.CharField(max_length=150, blank=False)
slug = models.SlugField(max_length=550, default="", null=False, blank=False)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=False, related_name="bottles")
每个Brand
都可以属于许多商家,每个Business
可以拥有多个品牌。
我的目标是,如果数据库中已存在Brand
个对象,则不会创建它们。
我构建了Bottle ModelForm
,它还允许用户在此过程中选择并创建新的Brand
。
但我现在面临的问题是:
X
→确定X
→IntegrityError唯一约束失败。我完全理解并且并不感到惊讶。我的问题是在这种情况下最好的解决方案是什么?
BottleCreateForm
非常标准:
class BottleCreateForm(ModelForm):
class Meta:
model = Bottle
fields = ['name', 'brand' , 'vintage', 'capacity']
但我还添加了一个“添加新”HTML按钮,该按钮调用品牌创建视图:
def add_brand(request):
response_data = {}
if request.method == "POST":
response_data['success'] = False
form = BrandCreateForm(request.POST)
if form.is_valid():
print("form valid!")
users_business = Business.objects.filter(owner=request.user).first()
form.save(commit=True)
users_business.brands.add(form.instance)
response_data['pk'] = form.instance.id
response_data['success'] = True
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
else:
response_data['errors'] = form.errors
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)