简体   繁体   中英

is there any way to create unique id's to particular field in django model

class Product(models.Model):
    name=models.CharField(max_length=128)
    category=models.ForeignKey('Category',on_delete=models.CASCADE)
    rate=models.IntegerField()
    peices=models.IntegerField(default=True)

    def __str__(self):
        return self.name
class Category(models.Model):
    name=models.CharField(max_length=128)
    def __str__(self):
        return self.name

here in the product model if i assign 100 integers to peices every piece should have a unique id
for eg: levis is a product and if i add 100 to the pieces section of this model so that i could get 100 different unique id's
i tried a lot googling it but its of no use
anykind of help is appreciated

In that case I think you need to create additional Piece model with:

class Piece(models.Model):

   product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='pieces')

And remove piece from Product. You can get all unique pieces from product with:

product = Product.objects.get(...) 
pieces = product.pieces.all()

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