外加入django模型。多对多关系

时间:2019-05-24 07:15:01

标签: python django postgresql django-models

我无法加入以下表格

我尝试了这些事情。 但是我仍然无法基于product_id加入CartDetail和Products表 我正在使用Django 2.1.7

    '''
    Product data model
    '''

    category = models.ManyToManyField(Category, blank=True)
    title = models.TextField(blank=False, null=False)
    created_by = models.ForeignKey(
        get_user_model(), on_delete=models.CASCADE)
    description = models.TextField(blank=False, null=False)
    price = models.FloatField(default=0.0, blank=False, null=False)
    product_image = models.ImageField(upload_to='images/', null=True)
    units_in_stock = models.IntegerField(default=1)
    created_at = models.DateTimeField(
        auto_now_add=True, blank=True, null=True)
    last_updated = models.DateTimeField(auto_now=True)
    last_updated_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, default=None,
                                        related_name='updated_by', null=True, blank=True)


class Cart(models.Model):
    '''
    Cart For User
    '''
    user_id = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
    product = models.ManyToManyField(Product, blank=True,through='CartDetail')
#    quantity = models.IntegerField(default=1, null=False, blank=False)



class CartDetail(models.Model):
    '''
    Further Data of Cart 
    '''
    product_id = models.ForeignKey(Product, on_delete=models.CASCADE)
    cart_id = models.ForeignKey(Cart, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1, null=False, blank=False)

    class Meta:
            '''
            To make Product Id and User Id Unique 
            '''
            unique_together = ('cart_id', 'product_id',)

0 个答案:

没有答案