Django 1.4.5 . Field relation

62 views Asked by At

I am new to django framework. I have 2 models:

class A(models.Model):
    name = models.CharField(...)
    position = models.PositiveSmallIntegerField(...)
    ...

class B(models.Model):
    myfield = ?
    ...

I want to make relation with "position" field and "myfield"(copy value from position to myfield, only with this fields).

How can i do this?

1

There are 1 answers

0
M.javid On BEST ANSWER

you must create relation between classes, you can doing this act by adding a models.OneToOneField or models.ForeignKey field of other class to the one of both classes and get access from one to other or vice versa and then implement myField in property form:

class A(models.Model):
    name = models.CharField(...)
    position = models.PositiveSmallIntegerField(...)
    ...

class B(models.Model):
    a_obj = models.ForeignKey(A, verbose_name="A instance that related to B instance")

    @property
    def myfield(self):
        return self.a_obj.position
    ...