开发者

Django ForeignKey issue

I have two classes

class A(models.Model):
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=200)
    store_id=models.IntegerField()
    type=models.ForeignKey(B)

class B(models.Model):
    id=models.IntegerField(primary_key=True)
    type=models.CharField(max_length=10)

 class C(models.Model):
    id=models.IntegerField(primary_key=True)
    store=models.CharField(max_length=200)

 class D(models.Model):
   id=models.In开发者_开发技巧tegerField(primary_key=True)
   type=models.CharField(max_length=10)

In my class A type is a ForeignKey on B and store_id is a logical foreign key on C or D depending upon the value of type.

In my field set I want to show the value of store depending upon typeafter some calculations. The type tells me about the table i.e C Or D and the vlaue of store tell me the row in that table c or d.Now i only want to show the value on the browser without overwriting the values.Is this possible?


Maybe you should look at Generic Relations.


If I got you correctly, then store_id always points to Cright? But this value depends on the type field?
If so you can set up a normal relation between those models and set the store_id based on the type field during saveing:

class A(models.Model):
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=200)
    store=models.ForeignKey(C)
    type=models.ForeignKey(B)

    def save(self,*args, **kwargs):
        if self.type == some_type:
            self.store = get_specific_store_here()
        super(A, self).save(*args, **kwargs)

And later you can access the store name by:

# a is an object of model A
a.store.store

If you want to stick with your generic integer field you can just add a custom method:

class A(models.Model):
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=200)
    store_id=models.IntegerField()
    type=models.ForeignKey(B)

    def get_store_name():
        store = C.objects.get(pk=self.store_id)
        return store.store
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜