Thursday, September 29, 2016

Re: Model Inheritance across apps

On 30/09/2016 10:33 AM, Malik Rumi wrote:
> Assume two models, class Parent(models.Model): and Child(Parent):
>
> Assume they are both in the same Project
>
> Can Child be in a different app than Parent? In most cases the answer
> seems to be yes.

True. You only need to import Parent. But it might be better to put them
both in their own app with Parent defined before Child.

>
> Each app has many other models to which Parent and Child,
> respectively, are closely tied - which is why they are in those apps.
>
> If so, what is the best practices way of doing so, and
>
> how does one avoid or minimize circular imports?

In the other apps you don't need to import Parent and Child for FK and
such. That completely avoids circular imports. If your Parent and Child
classes are defined in the parentchild app then you specify your FK like
this ...

class ThisThing(models.Model):
parent = models.ForeignKey("parentchild.Parent")
...

class OtherThing(models.Model):
child = models.ForeignKey("parentchild.Child")
...

> For example, if Child.models.py imports Parent in order to facilitate
> the inheritance, what do you do if another model in Parent.models.py
> has a fk to another model in Child.models.py?

You can also use quotes to specify the model class here. Just omit the
app name if they are in the same app.

Mike

> --
> 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
> <mailto:django-users+unsubscribe@googlegroups.com>.
> To post to this group, send email to django-users@googlegroups.com
> <mailto:django-users@googlegroups.com>.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/01251136-3cfb-4069-862c-78e118475958%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/01251136-3cfb-4069-862c-78e118475958%40googlegroups.com?utm_medium=email&utm_source=footer>.
> For more options, visit https://groups.google.com/d/optout.

--
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e7418590-1a87-518d-478a-1718463a2ce0%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment