TAGS :Viewed: 16 - Published at: a few seconds ago

[ creating 2 foreign keys that relate to one another ]

class Product(models.Model):  

    name = models.CharField(max_length = 127)   
    description = models.TextField()   
    code = models.CharField(max_length = 127)

    def __unicode__(self):
        return self.name


class ProductLot(models.Model):

    product = models.ForeignKey(Product)
    code = models.ForeignKey(Product)
    lot_no = models.CharField(max_length = 30)
    location = models.CharField(max_length = 127)
    incoming = models.IntegerField()
    commited = models.IntegerField()
    available = models.IntegerField()
    reorder = models.IntegerField()
    created_date = models.DateField(auto_now_add=True)

    def __unicode__(self):
        return self.product.name + " - " + self.lot_no

I want the code to correlate with product foreignkey so what you enter in for code correlates to the product.


ok Im trying to get a drop down box for the codes that correspond to a product. For example, when In Django I use the ForeignKey for a dropdown box that uses the products in the database but they also have a corresponding code number that doesn't show up in the code box as a dropdown box. I was thinking an embedded class code? Sorry I'm new to this

Answer 1


if you have two FK to one model you need to give different related names:

product = models.ForeignKey(Product, related_name='lot_product')
code = models.ForeignKey(Product, related_name='lot_code')

related_name comes from django docs:

ForeignKey.related_name

The name to use for the relation from the related object back to this one.

See the related objects documentation for a full explanation and example.

Answer 2


Make code a property that looks at product:

def getCode(self):
  return self.product and self.product.code

def setCode(self, value):
  if self.product:
    self.product.code = value
    self.product.save()

code = property(getCode, setCode)

You won't be able to use it in a query, but that's what product__code is for.

Answer 3


I think you should revise your models. Right now, each instance of ProductLot points exactly to two products. I'm not sure this is what you want.

It really depends on what the relation between code and product is. Some thoughts:

  1. Every Product has a unique code (1:1 relation):

    Just omit the second ForeignKey named code in model ProductLot.

  2. Every Product might have multiple different codes but each code only points to exactly one Product (1:n relation):

    I'd add another model for your codes such as:

    class Product(models.Model):
        name = models.CharField(max_length = 127)
        ...
    
    
    class ProductCode(models.Model):
        product = models.ForeignKey(Product)
        ...
    
    
    class ProductLot(models.Model):
        product_code = models.ForeignKey(ProductCode)
        ...
        def correspondingProductName(self):
            return self.product_code.product.name