开发者

Extending Django model class (m2m) 2 levels away

开发者 https://www.devze.com 2023-02-19 19:14 出处:网络
OK I know the title sounds really confusing, but really it\'s quite simple. Consider this: class A(models.Model):

OK I know the title sounds really confusing, but really it's quite simple. Consider this:

class A(models.Model):
    field = models.CharField(max_length=10)

class B(models.Model):
    field = models.CharField(max_length=10)
    a_elements = models.ManyToManyField(A)

class C(models.Model):
    field = models.CharField(max_length=10)
    b_element = models开发者_如何学C.ForeignKey(A)

so, now what I want is to extend all instances of A with some other field. for example for every instance of A that is available via B i need an integer associated to it.

is there an easy way of doing this?

EDIT:

I think one can see this as a definition of one-to-many relationship from C to instances of A in B, if that makes sense...


If you need to extend all instances of A with another field, add another field.

For your example scenario of needing a field for every A through B, use a through model.

http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships

class A(models.Model):
    field = models.CharField(max_length=10)

class B(models.Model):
    field = models.CharField(max_length=10)
    a_elements = models.ManyToManyField(A, through='B_A')

class C(models.Model):
    field = models.CharField(max_length=10)
    b_element = models.ForeignKey(A)


class B_A(models.Model):
    """
    Custom through model for B.a_elements
    """
    a = models.ForeignKey(A)
    b = models.ForeignKey(B)
    integer = models.IntegerField()


b = B.objects.latest('id')
ab_elements = B_A.objects.filter(b=b).select_related()
# these are your m2m intermediary model instances, 
# which are essentially A instances with an extra field.

for ab in ab_elemements:
    print ab.a # a element
    print ab.integer # integer associated with this a element.

By your question title, I think you're asking a question about C though (which you didn't mention)

0

精彩评论

暂无评论...
验证码 换一张
取 消