Tuesday, April 1, 2014

Re: ManyToMany quick question

Hello,

By using default table names and default (or automatic) many to many field management, you get a join table like countries_products, but in your case, you are doing the many to many field management through the Imports model, so in the DB you should see data in the imports table for each relation between Countries and Products.

When doing many to many in a relational model, as in a RDBMS or SQL database, that relation must be modeled by using a third table. This is in a normalized schema. So, you will not see a join field, but a join table. Note: in a non-normalized schema it is possible to have a field for a many to many relation, but with data duplication, not the case of the Django ORM.

So in your model you will never see a country_name field. Think of this: if the country table had a country_name field, you can only put one value in that field for every row, so only one value for any Django model in the ORM, and this is not many to many, but one to many.

In your case, the relation is in the Imports model and hence in the imports database table.

Regards,
Camilo

On Tuesday, April 1, 2014 5:51:18 AM UTC-4:30, willyhakim wrote:
Below is my models.py
My problem is when I syncdb (I have dropped the db couple times to start over)
the country_name field with m2m never shows in the db. what am I doing wrong? I am using postgres

class Products(models.Model):

    hs_number = models.CharField(primary_key=True, blank=True, max_length=4)
    product_descript = models.CharField(max_length=250)

    class Meta:
        db_table = "Products"

    def __unicode__(self):
        return self.hs_number


class Countries(models.Model):
    country_id = models.CharField(primary_key=True, max_length=2, blank=True)
    country_name = models.ManyToManyField(Products, through="Imports", blank=True)
    region = models.CharField(max_length=200)

class Imports(models.Model):
    hs_number = models.ForeignKey(Products)
    country_id = models.ForeignKey(Countries)
    imported_value2008 = models.DecimalField(max_digits=12, decimal_places=2, default=0.00)
    imported_value2009 = models.DecimalField(max_digits=12, decimal_places=2, default=0.00)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0fb3823a-414e-4255-85f8-48acfa21878a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment