A little question about one of the most useful django frameworks:
django.contrib.sites
Assuming I have a model:
class MyModel(models.Model):
info = models.TextField()
site = models.ManyToManyField(Site)
objects = models.Manager()
on_site = CurrentSiteManager()
and another model, that's linked to the given above:
class MyModelSupplement(models.Model):
info = models.TextField()
parent_model = models.ForeignKey(MyModel)
Scheme specifies, that MyModelSupplement can't belong to sites, it's parent doesn't belong to.
having this structure I can access MyModel object on the given site simply by invoking
MyModel.on_site.all()code. What's the best way to achieve the same on MyModelSupplement model?
I can think of a few ways to solve this:
MyModelSupplement.objects.filter(parent_model__site__id = some_site_id)
MyModel.on_site.all().values_list('mymodelsupplement')
Or even go to this variant: my_models = MyModel.on_site.all() \nmy_models_supplements = MyModelSupplements.objects.filter(parent_model__in=my_models).select_related()
is there a better way of accomplishing the mentioned task? The note is that I need to access both this models both together and separately, trying to retrieve instances respected to the given site?
Maybe there's a way to say something like: all SiteID values from MyModel
should be in MyModelSupplement
. If SiteID value was deleted from MyModel
instance, it should be deleted from all MyModelSupplements
, that are related to the the respected MyModel
instance with ManyToMany relationship.
Is that achievable?
I was able to solve this problem the following way:
this goes before everything happens:
from django.conf import settings
after that, we create a custom manager:
class OnSiteMyModelSupplementManager(models.Manager):
def get_query_set(self):
return super(OnSiteMyModelSupplementManager, self).get_query_set().filter(parent_model__sites=settings.SITE_ID)
and simply putting two more lines of code into MyModelSupplement class:
objects = models.Manager()
on_site = OnSiteMyModelSupplementManager()
and now I'm capable of retrieving MyModelSupplements, that belong only to the current web-site, as there parents do.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.