Django M2M Through extra fields with multiple models

2024/10/14 19:25:01

I'm trying to figure out the best way to set up the following django model (genericised for security reasons).

ThingA:User(M2M through "UserRelation")ThingB:User(M2M through "UserRelation")ThingC:User(M2M through "UserRelation")User:Login_nameUserRelation:User (foreginkey)Thing (foreignkey) #is this generic to any of the above "things"Privilege

I understand using "through" between two distinct models, but I'm not sure how to apply this to multiple models. Would I define a foreignkey for each of the "Thing" models in my UserRelation Model?

Answer

It looks like you are trying to setup a generic many-to-many relationship. There is a dedicated django app that you can be use for this purpose: django-gm2m

Here is how to use it in your generic case:

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKeyfrom gm2m import GM2MFieldclass ThingA(models.Model):passclass ThingB(models.Model):passclass ThingC(models.Model):passclass User(models.Model):login_name = models.CharField(max_length=255)things = GM2MField(through='UserRelation')class UserRelation(models.Model):user = models.ForeignKey(User)thing = GenericForeignKey(ct_field='thing_ct', fk_field='thing_fk')thing_ct = models.ForeignKey(ContentType)thing_fk = models.CharField(max_length=255)privilege = models.CharField(max_length=1)

You can now access all the things for a given user and all the User instances for a given 'thing', as well as the privilege attribute for each UserRelation instance.

This will additionally provide you with a handful of benefits (reverse relations, prefetching, etc.) you may need. A GM2MField basically behaves exactly like a django ManyToManyField.

Disclaimer: I am the author of django-gm2m

https://en.xdnf.cn/q/117921.html

Related Q&A

Openpyxl: Worksheet object has no attribute values

My goal is to read in an excel file and view the codes in a pandas dataframe (i.e. = A3) rather than the resulting values from excel executing the codes, which is the pandas default if read in using pa…

Calculation of Contact/Coordination number with Periodic Boundary Conditions

I have data for N atoms including the radius of each atom, the position of each atom and the box dimensions. I want to calculate the number of atoms each atom is in contact with and store the result. T…

how can I export multiple images using zipfile and urllib2

I am trying to add multiple image files into my zip. I have searched around and knows how to add a single one. I tried to loop through multiple images then write into it but it didnt work. I kind of d…

XPATH for Scrapy

So i am using SCRAPY to scrape off the books of a website. I have the crawler working and it crawls fine, but when it comes to cleaning the HTML using the select in XPATH it is kinda not working out ri…

Kivy Removing elements from a Stack- / GridLayout

I made a pop-up. It is basically some rows of options (max. 5 rows).If I press the + button, there will be a new line of options.If I press the - button the last row should diasappear. Unfortunatelly i…

Bad timing when playing audio files with PyGame

When I play a sound every 0.5 second with PyGame:import pygame, timepygame.mixer.init() s = pygame.mixer.Sound("2.wav")for i in range(8):pygame.mixer.Channel(i).play(s)time.sleep(0.5)it doesn…

Using read_batch_record_features with an Estimator

(Im using tensorflow 1.0 and Python 2.7)Im having trouble getting an Estimator to work with queues. Indeed, if I use the deprecated SKCompat interface with custom data files and a given batch size, the…

How to insert integers into a list without indexing using python?

I am trying to insert values 0 - 9 into a list without indexing. For example if I have the list [4, 6, X, 9, 0, 1, 5, 7] I need to be able to insert the integers 0 - 9 into the placeholder X and test i…

Separate/reposition/translate shapes in image with pillow in python

I need to separate or translate or replace pixels in an image with python so as to all the shapes to share the same distance between each other and the limits of the canvas.background is white, shapes …

django.db.utils.OperationalError: (1045, Access denied for user user@localhost

I cant get my Django project to load my database correctly. It throws this error. Im running MariaDB with Django, and I uninstalled all MySQL I added the user by running:create database foo_db; create …