简体   繁体   中英

Referencing foreign key in Django Python

How to assign a product in ProductInStore to an instance of a Product already in store? Basically i have a scrapper and im looping through all the products and i need to first create the Product instance, and then A ProductInStore instance which is connected to Product via foreignKey. And when i try to put in ProductInStore(product=id) thats how i wanted to reference that Product, i get an error ValueError: Cannot assign "11393": "ProductInStore.product" must be a "Product" instance. Do you have any idea how to reference it?

class Product(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True, null=False, editable=False)
    created_at = models.DateTimeField(editable=False, default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)
    product_category = models.ManyToManyField(EcommerceProductCategory)
    description = RichTextField(max_length=2000, null=True, blank=True)
    product_producer = models.ForeignKey('ProductProducer', on_delete=models.CASCADE)
    creator = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, blank=True, related_name='product_creator')
    points_from_reviews = models.DecimalField(max_digits=6, decimal_places=2, default=0, help_text='Średnia ocena produktu')
    unique_id = models.CharField(max_length=256, unique=True)
    type_of_unique_id = models.CharField(max_length=64)
class ProductInStore(models.Model):
    product = models.ForeignKey('Product', on_delete=models.CASCADE)
    store = models.ForeignKey('Store', on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=6, decimal_places=2, default=0, help_text='Cena w sklepie')
    currency = models.CharField(max_length=4)
    url = models.CharField(max_length=200)
    created_at = models.DateTimeField(editable=False, default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)
    # ADD TO DATABASE
                try:
                    db_product = Product.objects.create(name=name, slug=slug, product_producer_id=3, unique_id=id,
                                                description=description)
                    db_product.product_category.set(parsed_categories)
                except:
                    print('product already in database')

                ProductInStore.objects.create(product=,store=1,price=price,currency='PLN',url=url)

You can simply do this:

ProductInStore.objects.create(product_id=id, store=1, price=price, currency='PLN', url=url)

You don't need to pass the object if you have the ID of it, simply append _id to the field name and you can reference the foreign key that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM