using data of queyset as input values of another model

Hi every one
i have two models
one for saving product data

class Good(models.Model):
    mainbranch = models.ForeignKey(
        MainBranch, on_delete=models.CASCADE,
        verbose_name='کد دسته اصلی', default=0
    )
    subbranch1 = models.ForeignKey(
        SubBranch1, on_delete=models.CASCADE,
        verbose_name='کد دسته فرعی 1', default=0
    )
    subbranch2 = models.ForeignKey(
        SubBranch2, on_delete=models.CASCADE,
        verbose_name='کد کالا', default=0
    )
    subbranch3 = models.ForeignKey(
        SubBranch3, on_delete=models.CASCADE,
          verbose_name='نام کالا', default=0, related_name='good_name')
    goodproperties = models.OneToOneField(
        GoodProperties, on_delete=models.CASCADE,
        verbose_name='مشخصات کالا', null=True, blank=True
    )
    goodspecifications = models.OneToOneField(
        GoodSpecification, on_delete=models.CASCADE,
        verbose_name='معرفی کالا', default=0, null=True, blank=True
    )    
    image = models.ImageField(upload_to='photos/%Y/%m/%d', null=True, blank=True, verbose_name='تصویر کالا')
    quantity = models.PositiveIntegerField(default=0, verbose_name='تعداد موجود')
    price = models.DecimalField(
        decimal_places=0, max_digits=12, default=0,
        verbose_name='قیمت کالا'
    )
    discount = models.SmallIntegerField(null=True, blank=True, verbose_name='میزان تخفیف')
    seller = models.ManyToManyField('Seller', verbose_name='کد فروشنده')

and one for saving customers buy basket data

class BuyBasket(models.Model):
    customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True,
                                       verbose_name='کد مشتری')
    mainbranch = models.ForeignKey(
        MainBranch, on_delete=models.CASCADE, verbose_name='کد دسته اصلی کالا', default=0) # type: ignore
    subbranch1 = models.ForeignKey(
        SubBranch1, on_delete=models.CASCADE, verbose_name='کد دسته فرعی 1 کالا', default=0) # type: ignore
    subbranch2 = models.ForeignKey(
        SubBranch2, on_delete=models.CASCADE,verbose_name='کد دسته فرعی 2', default=0) # type: ignore
    subbranch3 = models.ForeignKey(
        SubBranch3, on_delete=models.CASCADE,verbose_name='نام کالا',default=0
    ) # type: ignore
    quantity = models.PositiveIntegerField(verbose_name='تعداد')
    price = models.ForeignKey(Good, on_delete=models.CASCADE, default=0, verbose_name='قیمت کالا') # type: ignore
    total_price = models.DecimalField(decimal_places=0, max_digits=16, default=0, verbose_name='مبلغ کل سفارش') # type: ignore
    change_to_order = models.BooleanField(blank=True, null=True, verbose_name='تبدیل به سفارش')

also this piece of code in my views.py that is going to add a product to customer’s basket

def add_to_buybasket(request, g_id):
    good_item = Good.objects.get(id=g_id) 
    if request.method == 'POST':
        form =QuantityForm(request.POST)
        if form.is_valid():
            value = form.cleaned_data['quantity']     
    obj, created = BuyBasket.objects.update_or_create(
        customer_id = request.user.id,
        mainbranch_id = good_item.mainbranch.id,
        subbranch1_id = good_item.subbranch1.id,
        subbranch2_id = good_item.subbranch2.id,
        subbranch3_id = good_item.subbranch3.id,        
        quantity = value,
        price_id = good_item.price, # here the problem appears
        total_price = value * good_item.price,
        change_to_order = False,
    )
    messages.success(request, 'کالا به سبد خرید شما اضافه شد')
    return HttpResponseRedirect(reverse('goods_list', kwargs={'pk': g_id}))

the problem is when i want to set price field of BuyBasket model with the value of corresponding Good one Django throws this error

insert or update on table "orders_buybasket" violates foreign key constraint "orders_buybasket_price_id_bbb4aff1_fk_goods_good_id"
DETAIL:  Key (price_id)=(18000000) is not present in table "goods_good".

Could you tell me where the problem is
Thanks

In model Good, you have:

But in model BuyBasket you have:

The price field is expecting to be assigned a reference to an instance of a Good object, not the result of a calculation. I expect that what you want is for this second occurrance of price to be a decimal field similar in structure to the price field of the Good model.

Thaks for your answer
yes you are right
so should i define BuyBasket price as a normal decimal field?

To add on @KenWhitesell i also think you should consider to properly design you models/tables. Here are some modification have made if you can take a look

BRANCH_TYPES = [
    ("MAIN_BRANCH", "MAIN_BRANCH"),
    ("SUB_BRANCH", "SUB_BRANCH"),
]



class Branch(models.Model):
    branch_name = models.CharField(default='', max_length=9000)
    branch_type = models.CharField(default='', choices=BRANCH_TYPES, max_length=9000, null=True)

class Good(models.Model):
    branch = models.ForeignKey(Branch, on_delete=models.CASCADE,related_name = "good_branch", verbose_name='کد دسته اصلی', default=0)
    goodproperties = models.OneToOneField(GoodProperties, on_delete=models.CASCADE,verbose_name='مشخصات کالا', null=True, blank=True)
    goodspecifications = models.OneToOneField(GoodSpecification, on_delete=models.CASCADE,verbose_name='معرفی کالا', default=0, null=True, blank=True)    
    image = models.ImageField(upload_to='photos/%Y/%m/%d', null=True, blank=True, verbose_name='تصویر کالا')
    quantity = models.PositiveIntegerField(default=0, verbose_name='تعداد موجود')
    price = models.DecimalField(decimal_places=0, max_digits=12, default=0,verbose_name='قیمت کالا')
    discount = models.SmallIntegerField(null=True, blank=True, verbose_name='میزان تخفیف')
    seller = models.ManyToManyField('Seller', verbose_name='کد فروشنده')
    
       
    
class BuyBasket(models.Model):
    customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True,       verbose_name='کد مشتری')
    quantity = models.PositiveIntegerField(verbose_name='تعداد')
    good = models.ForeignKey(Good, on_delete=models.CASCADE, default=0, verbose_name='قیمت کالا') # type: ignore
    total_price = models.DecimalField(decimal_places=0, max_digits=16, default=0, verbose_name='مبلغ کل سفارش') # type: ignore
    change_to_order = models.BooleanField(blank=True, null=True, verbose_name='تبدیل به سفارش')

Changes:-

  1. I introduce new model called Branch which will give you ability to dynamically add new sub-branch like subbranch1, subbranch2, subbranch3, subbranch4
  2. In BuyBasket i remove branches fields since good field is already linked to branch.
  3. The price on the BuyBasket model has no use since Good has its price

Thank you for your time spending for redefining models
it is really helpful and i learned from it

an other thing i though about ypur modifications is to add another field to Branch call it superbranch
because every branch with bigger number in last part of its name (subbranch2 has a bigger number compare to subbranch1 and …) is a subset of branch with smaller number in last part of its name
so for example subbranch1 is superbranch for subbranch2 and subbranch2 is subset of subbranch1