Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django manytomany relationship over 2 apps

I'm trying to create a relationship where a clients can favorite vendors and stores, and on my class diagram (see bellow image) i have the following relations:

In the first app i have a person object, which is inherited by vendor and client In the second app i have only a store object (Which have backwards relation to vendor, but it's not show on class diagram, this is the reason that's the second app to be instantied)

The problem is that client have manytomany relation to vendor and another manytomany relation to store, but the relation client/store generate a error, cause the app2 is isntantied after app 1.

Is there any way to make generic manytomany relation?

Cause clients can have many vendors and many stores, stores can have many clients, and vendors can have many clients

class diagram

The code i used:

class Store(models.Model):
    name = models.CharField("Nome", max_length=100)
    description = models.CharField("Descrição", max_length=300)

    class Meta:
        app_label = 'store'

class Person(models.Model):
    first_name = models.CharField("Primeiro Nome", max_length=100)
    last_name = models.CharField("Ultimo Nome", max_length=100)

    class Meta:
        app_label = 'core'


class Vendor(Person):
    bio = models.TextField("Bio", max_length=300, blank=True)
    last_update = models.DateTimeField("Ultima Atualização", auto_now=True)

    class Meta:
        app_label = 'core'


class Client(Person):
    favorite_stores = models.ManyToManyField(Store)
    favorite_vendors = models.ManyToManyField(Vendor)

    class Meta:
        app_label = 'core'

This code give me the following error:

self.models_module = import_module(models_module_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/core/models.py", line 7, in <module>
    from store.models import Store
  File "/store/models.py", line 6, in <module>
    from core.models import Vendor

And what i want to see in the admin is simple as that: admin

like image 809
Yuri Heupa Avatar asked Jan 09 '23 15:01

Yuri Heupa


1 Answers

just add two ManyToMany relations, instead of importing the "Store" model, use a string directly (to avoid circular dependency)

class Client(Person):
   favorite_stores = models.ManyToManyField('store.Store')
   favorite_vendors = models.ManyToManyField(Vendor)
like image 70
Rafael Sandrini Avatar answered Jan 16 '23 22:01

Rafael Sandrini