Reputation: 71
class ProductGroup(models.Model):
group_sku = models.CharField(unique=True, max_length=255)
brand = models.CharField(max_length=255)
...
class Product(models.Model):
product_sku = models.CharField(unique=True, max_length=255)
color = models.CharField(max_length=255)
size = models.CharField(max_length=255)
product = models.ForeignKey(Product, limit_choices_to=Q(group_sku__in=product_sku))
...
I'm importing my data to Django from an XML file via a python script.
group_sku comes in the format "GROUP123"
product_sku comes in the format "GROUP123-BLUE-M" (or similar) and there are multiple products in each group
How do I define the foreign key relationship so that each Product is linked to its respective ProductGroup? Or feel free to tell me if I'm going about this the complete wrong way.
Using Django 1.6.5, Python 2.7, and MySQL
Upvotes: 1
Views: 447
Reputation: 2136
The models should be defined like this. With the Product group field with ForeignKey to Group, meaning Product belongs to Group.
class ProductGroup(models.Model):
group_sku = models.CharField(unique=True, max_length=255)
brand = models.CharField(max_length=255)
...
class Product(models.Model):
product_sku = models.CharField(unique=True, max_length=255)
color = models.CharField(max_length=255)
size = models.CharField(max_length=255)
group = models.ForeignKey(Group)
In your script, you should get all groups first and create them, then parse (you could use regular expressions for this) the product_sku to know which group it belongs to. You'll have to have something like:
# save group
group = Group(group_sku=group_sku_from_xml, ...)
group.save()
# later that script...
group_sku = get_group_from(product_sku_from_xml)
group = Group.objects.get(group_sku=group_sku)
# save product
product = Product(group=group, product_sku=product_sku_from_xml, ...)
product.save()
Upvotes: 1