Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter in django using condition
I have 4 file uploading fields (only one file is mandatory for uploading) and 4 status corresponding to each file. There is a filter in front end called 'Completed' to filter the dashboard. How to filter records which are completed (Completed status only if there is a file and its status need to be True, if 4 file are uploaded then all of the corresponding status of each file need to be True to consider as completed.No matter the person uploaded 1 or 4 files based on the files uploaded the corresponding file status need to be true. Table column example file1 | file1_status | file2 | file2_status | file3 | file3_status | file4 | file4_status -
django bulk insert using value from parent table instead of ID
I have 2 models -- AssetType and Asset (both have IDs and Asset has a foreign key point to AssetType) I want to bulk insert rows in the Asset table using Asset Type NAME, instead of ID. I tried to do df.to_sql() but it can't work because my df contains "asset type name" instead of asset type id. Is there a way to convert it easily? Expected Output The asset type table looks like this: id | name | description 1 | at1 | desc1 The Asset table should look like this asset_name | display_name | asset_type_id n1 | d1 | 1 The dataframe I want to insert in the Asset table looks like this (Input): asset_name | display_name | asset_type_name n1 | d1 | at1 So, I am passing in at1 in my dataframe but want to insert it as "id=1" for asset type. Is this possible in django? My models are: class AssetType(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=80, unique=True) description = models.CharField(max_length=80) class Asset(models.Model): asset_type = models.ForeignKey(AssetType, on_delete=models.CASCADE) asset_name = models.CharField(max_length=80) display_name = models.CharField(max_length=80) My serializer looks like this: class AssetTypeSerializer(serializers.ModelSerializer): class Meta: model = AssetType fields = "__all__" class AssetSerializer(serializers.ModelSerializer): asset_type_name = serializers.CharField(source='asset_type.name') class Meta: model … -
how to insert a floating value as binary numbers and retrieve as floating value in MySQL
how to insert a floating value as binary numbers and retrieve as floating value in MySQL, python, Django like I have a floating value 2000.252 I need store it on MySQL column as binary 010101 or string 'sddg121fg' or encryption 'dgdfggdfgttzzd' but when I retrieve this value it will be 2000.252 -
How to Use Django Queryset update() function with foreign key field cited by F()?
I want to make a simple query: with transaction.atomic(): Account.objects.select_for_update().filter(payments__status='PENDING', payments__created_date__lt=timezone.now()-timedelta(days=14)).update(balance=F('balance')+Sum(F('payments__amount') - F('payments__payment_fee__fee_amount')), payments__status='COMPLETED') It turned out it wasn't simple at all. I've tried Subquery but alternatively get "Joined field references are not permitted in this query" or "FOR UPDATE is not allowed with GROUP BY clause" Subquery doesn't work because aggregation doesn't work with select_for_update() locks. F() doesn't work because it is referencing foreign key fields... What's the best way to make this query work? Any idea? I am using postgresql behind the ORM. -
Django/SpaCy: Cannot import module outside of its root directory in Python
I am stumped trying to import and call this NLP package from outside of its root directory https://github.com/msg-systems/coreferee. I doubt it has anything to do with package and probably has everything to do with my not understanding how Python modules work. Here is a scenario: I cloned coreferee into a subdirectory of my Django project (/api/libs/coreferee). If I terminal into the root directory of the package, I can run the following test script fine: test.py in root of coreferee module at ./api/libs/coreferee import spacy import coreferee nlp = spacy.load("en_core_web_trf") nlp.add_pipe('coreferee') # passes the coreferee module as transformer doc = nlp("Although he was very busy with his work, Peter had had enough of it. He and his wife decided they needed a holiday. They travelled to Spain because they loved the country very much.") doc._.coref_chains.print() However, if I try to import coreferee from anywhere else in my application, I get a bad reference and the test script errors out. test.py at ./api/ import spacy from api.libs import coreferee spacy.prefer_gpu() nlp = spacy.load("en_core_web_trf") # en_core_web_lg nlp.add_pipe('coreferee') # this produces an error ValueError: [E002] Can't find factory for 'coreferee' I am stumped. -
How to exclude some data from values_list in Django?
I'm using checkbox filtering to filter the data in Django. While I want to exclude some data from checkbox filtering for example I have 5 brands SAMSUNG NOKIA MI IPHONE LG from the above list, I don't want MI should include in my checkbox list. So, How to exclude such data. forms.py class BrandForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) brand = Brand.objects.filter(category=3).values_list('name', flat=True) for name in brand: self.fields[f'{name}'] = forms.BooleanField(label=f'{name}',widget=forms.CheckboxInput(required=False) -
Follow Button in Django
I'm new to django and creating a follow button where users can follow a certain profile. When I click 'follow' on the profile, currently I don't get any errors at all. Nothing happens. I don't see anything in my console. There's no error. Am I missing something obvious? No matter what I put in views.py nothing happens. So I don't think it's that. Is it my url? urls.py urlpatterns = [ path("", views.index, name="index"), path("fol/<str:username>", views.fol, name="fol"), path("profile/<str:username>", views.profile, name="profile"), ] models.py class User(AbstractUser): pass class Post(models.Model): text = models.TextField(max_length=500, blank=True, null=True) username = models.ForeignKey('User', on_delete=models.CASCADE, related_name='author', null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField( User, blank=True, related_name="liked_user") def __str__(self): return self.user.username class Follow(models.Model): target = models.ForeignKey('User', on_delete=models.CASCADE, related_name='followers') follower = models.ForeignKey('User', on_delete=models.CASCADE, related_name='targets') html {% extends "network/layout.html" %} {% load static %} {% block body %} <h3> You are viewing {{ profileuser.username }}'s profile. </h3> <br> <br> <br> <br> {% if user1 != user2 %} <div class="pull-right"> <a href="{% url 'fol' username=profileuser.username %}"></a><input class="btn btn- primary" type="submit" value="Follow"> </div> <br><br> <div class="pull-right"> <input class="btn btn-primary" type="submit" value="Unfollow"> </div> {% endif %} {% for i in page_obj %} <div class='card mb-3' style="max-width: 530px;" id="card-posts"> <div class="row no-gutters"> <div class="col-md-8"> <div … -
Import cannot be resolved pylance error in vscode, have tried a few fixes
I am having trouble using pylint for my Django app. I am receiving a couple of errors and have resolved some using other threads but the main one I am still running into is Import ".forms" could not be resolved. I am hitting this error inside the views.py file when trying to import from forms.py with the following import from .forms import ArtistForm (ArtistForm being a class). I have tried following the below resources but have not been very successful. https://github.com/microsoft/pylance-release/blob/main/TROUBLESHOOTING.md#unresolved-import-warnings This is what I added to my .vscode/settings.json to try and resolve with the above - "python.analysis.extraPaths": ["tunr/", "./tunr/templates/tunr"] I also tried using the .env fix detailed in the below article - https://appdividend.com/2021/03/26/python-unresolved-import/ I am new to coding so I have been having trouble fully understanding how to fix this. Any help is appreciated. Below is my file structure, not the tunr folder is at the root: tunr ├── apps.py ├── models.py ├── templates │ └── tunr │ ├── artist_detail.html │ ├── artist_form.html │ ├── artist_list.html │ ├── base.html │ ├── forms.py │ ├── song_detail.html │ └── song_list.html └── views.py Let me know if any other information will be helpful. -
Django List View Sorting Bulletins
I have a ListView of bulletins I am trying to provide ordering options for. I am using a dropdown to pass a URL parameter called sortBy. I have confirmed via my print statement at the end of def get(self, request): that the order of the queryset changes as expected when different values are passed to sortBy. The problem I am facing is that even though the order of the queryset is changing as expected, this is not being reflected in myTemp.html. The order of the bulletins being displayed are not changing even though the order of the queryset is. What is causing this behavior? Views.py @method_decorator(login_required, name='dispatch') class BulletinList(ListView): model = Bulletin_VW template_name = 'myTemp.html' context_object_name = 'bulletins' additional_context = {} @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_queryset(self): queryset = Bulletin_VW.objects.filter(store_id=self.additional_context['storeID'], entity_id=self.additional_context['entityID']) ordering = self.get_ordering() queryset = queryset.order_by(ordering) return queryset def get_context_data(self, *args, **kwargs): self.object_list = self.get_queryset() context = super(BulletinList, self).get_context_data(*args, **kwargs) context.update(self.additional_context) return context def get_ordering(self): ordering = self.request.GET.get('sortBy', 'Name') sortDict = {'Name': 'author', 'Date-Newest': '-capture_date', 'Date-Oldest': 'capture_date'} ordering = sortDict.get(ordering) return ordering def get(self, request): if not validate_user_session(request.user.id): return redirect('newSession') currentSession = Current_Session_VW.objects.filter(user_id=request.user.id)[0] storeID = currentSession.store_id entityID = currentSession.entity_id entStore = currentSession.entity_store_name balance = get_balance(storeID, … -
Redirect in Django giving 302 response
What I am trying to do is prevent an authenticated user from accessing the signup page. This is what I have written. def validate_request(request): if request.user.is_authenticated and request.user.is_active: print("Condition approved") return redirect("home:home") def signup_view(request): validate_request(request) if request.method == "POST": form = StudentUserSignupForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect("student:email_confirmation") else: redirect("home:home") else: print("Got some other method: ", request.method) form = StudentUserSignupForm() context = { "form": form, } return render(request, "signup_login_form.html", context=context) When I test and create a new user, it gets created successfully and is redirecting fine. However, the new user created is still able to access the signup page. I added some quick print statements at the redirect function call inside validate_request function and the output was <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/"> The URL it was trying to check for is already present and is correct. I replaced the redirect to https://google.com instead of home:home and it still gave the same response. The third thing tried was to redirect as soon as the signup_view function is called. That too was failing with the same response with both internal redirect and redirecting to Google. I have been stuck on this problem for a while. I have gone through … -
FCM django installation error python 3.6.9
Installing fcm-Django on my local was fine, but on the server, I am getting errors. File "/opt/pythonprojects/env/lib/python3.6/site-packages/setuptools/command/build_ext.py", line 203, in build_extension if ext._needs_stub: AttributeError: 'Extension' object has no attribute '_needs_stub' File "/tmp/pip-build-re2xfk5h/grpcio/src/python/grpcio/support.py", line 98, in diagnose_attribute_error "We expect a missing `_needs_stub` attribute from older versions of " commands.CommandError: We expect a missing `_needs_stub` attribute from older versions of setuptools. Consider upgrading setuptools. Command "/opt/pythonprojects/env/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-re2xfk5h/grpcio/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-ljbtkbh4-record/install-record.txt --single-version-externally-managed --compile --install-headers /opt/pythonprojects/payrink-env/include/site/python3.6/grpcio" failed with error code 1 in /tmp/pip-build-re2xfk5h/grpcio/ Also setuptools is up-to-date on my server which I updated several times. Also tried to install grpcio manually but had no success. Python 3.6.9 -
Django update rows base on order in queryset
I have a simple django model class Item(Model): name = CharField() rank = PositiveIntegerField() created_at = DateField(auto_now_add=True) I want to update the object rank based on their order when sorted by a field (name or created_at) e.g. when ordering by name [("Pen", 0, "2021-05-04"), ("Ball", 0, "2021-05-04")] => [("Pen", 1, "2021-05-04"), (Ball, 0, "2021-05-04")] I already know I can do this using bulk_update but it means I have to fetch the objects in memory items = Items.objects.order_by("name") for i, item in enumerate(items): item.rank = i Item.objects.bulk_update(items, ["rank"]) I was wondering if there is a way to do it with 1 query directly in the database, without having to fetch the data -
For if Loop ManyToMany Field Django
How can I query a manytomanyfield in a Django template? For example, this if statement doesn't work, but this shows what I'd like to do: Model: class Product(models.Model): Category = models.ManyToManyField(Category) Template: {% for p in Product %} {% if p.Category_id == 6 %} {{p.id}} {% endif %} {% endfor %} -
sys.settrace disabling needed or not
The backend REST service I am working is written in python/django and sometimes the server crashes due to one request without reporting the exception i.e. can't even know which line it was where it last reached. The application does not have any function entry/exit logs which could be enabled by environment config so alternative I have come up with was I will enable sys.settrace based on a custom request header. So, I have written something like this in one of the request middleware: def debug_tracer(frame, event, arg = None): code = frame.f_code func_name = code.co_name line_no = frame.f_lineno print(f"A {event} encountered in \ {func_name}() at line number {line_no} ") return debug_tracer if.requests.headers.get("HTTP_TRACEBACK"): sys.settrace(debug_tracer) It behaves like this for a single server deployment: Request at t=1 without traceback header -> Plain request-response logs Request at t=2 with traceback header -> Every line of execution gets into logs along with request-response logs Request at t=3 without traceback header -> Plain request-response logs This is working fine right now, i.e. whenever I pass a header with traceback key, the logs for that particular request contain the details calls/returns/lines. But I am not able to understand that without doing sys.settrace(None) i.e. actively disabling the … -
How to setup alias in Nginx
I deployed a django application using Digital ocean plateform. When nginx was serving static files through roots everything worked fine. But the moment installed boto3 and Django_storage and turned to alias nginx stopped serving the static files. I saw that similar question was asked but I still don't understand why the static files are not been served. After running python manage.py collectstatic the staticfiles appeared in the folder in digital ocean space but the staticfiles are not being served on the browser. My project structure is as follows: $myprojectdir/ myproject/ settings.py static/ manage.py ... settings.py AWS_ACCESS_KEY_ID = '***' AWS_SECRET_ACCESS_KEY = '***' AWS_STORAGE_BUCKET_NAME = '*** AWS_S3_ENDPOINT_URL = '***' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = '***' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' sudo vim /etc/nginx/sites-available/myproject server { server_name domain; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/sammy/myprojectdir/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/api.flolog.co/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/api.flolog.co/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host … -
count duplicate words in arrayField of postgres django
In my django's array field Is there any way I can count how many duplicate elements there are in the query_set query? For example, I have tags ["A", "B", "C"] Each object you query in the list will know how many characters it matches Object 1 with tags ["A", "B", "F"] has the same 2 Object 2 with tags ["H", "S", "B"] has the same 1enter image description here -
Setup user role read/edit project by project, Django ORM
I am trying to implement a relationship between three tables; User Project and Permissions I already have a ManyToMany relationship between User and Project class CustomUser(AbstractUser): username = models.CharField(unique=True, max_length=20, null=False, blank=False) // etc... class Project(models.Model): user = models.ManyToManyField(CustomUser, related_name="projects") Now I am trying to add the Permission Table. So that User can take different roles on different project. class Permissions(models.Model): can_read = models.BooleanField(default=True) can_read_and_edit = models.BooleanField(default=False) // etc... What is the best approach on this situation. Should I Add Permission table into manytomany relation as a third table? Or is there a better way to achieve this -
Django recursive relationship in many-to-one and many-to-many
I'm reading Django documentation and currently trying to understand the Django models recursive relationship in many-to-many and many-to-one and I still don't get it. Can anybody help to explain in what situation we need to use recursive relationship? And how will the recursive many-to-one be different from the recursive many-to-many? Will be great if perhaps in an example. Thank you in advance. -
How to use string values of a variable as a django model queries?
I have some Model Fields those are related to User model by many to many relationship class SocialPost(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE, related_name='users_post' ) privacy=models.CharField(max_length=100,blank=True, null= True) post_text=models.TextField(blank=True, null= True) location=models.CharField(max_length=100,blank=True, null= True) feeling_or_activity=models.CharField(max_length=100,blank=True, null= True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(blank=True,null=True) category=models.CharField(max_length=100,blank=True, null= True) tags=models.ManyToManyField(User, related_name='taglist',blank=True) views = models.ManyToManyField(User, related_name='post_views',blank=True) likes = models.ManyToManyField(User,related_name='post_likes',blank=True) love=models.ManyToManyField(User,related_name='post_loves',blank=True) angry=models.ManyToManyField(User,related_name='post_angries',blank=True) haha=models.ManyToManyField(User,related_name='post_hahas',blank=True) sad=models.ManyToManyField(User,related_name='post_sads',blank=True) care=models.ManyToManyField(User,related_name='post_cares',blank=True) senti=models.ManyToManyField(User,related_name='post_senties',blank=True) wow=models.ManyToManyField(User,related_name='post_wows',blank=True) I will get values like reaction='wow' through API call. i want to call like variable=object.reaction.filter() Which will be always call by reaction variables value. as example if reaction='like' it will call variable=object.like.all() and if reaction='sad' it will call variable=object.sad.all() i don't know how can i do this! can anyone help me in this problem? -
Javascript/Jquery: How we can use loading spinner for download some report from our web-page
I'm Just stuck with some problem which is "Generate Report". It actually download the report and it takes time to generate and download the report. So I just want to use loading spinner for that download file. I'm new to understand the concept of Javascript/Jquery. In this logic, I haven't used any ajax request. Also I've 2 files like i.e. .html file and .js, Please suggest me how to solve this logic. I've explored everywhere, couldn't find anything. -
How to automatically set the thread instead of user having to set it in django
I am trying to create a discussion forum website with django. Everything is working, but I want to change one thing and I have no idea how to. In the website users can create threads and posts inside those threads. When a thread is created there is a button in that thread that says add a post in this thread. Then it will take them to a form. Right now, if the form were to work they would have to select from a dropdown menu which thread they wanted to add a post to. I want the thread to be the thread that the button they clicked was inside of. models.py: class Thread(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) description = models.CharField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('thread-view', kwargs={'pk': self.pk}) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) thread = models.ForeignKey(Thread, on_delete=models.CASCADE) title = models.CharField(max_length=300) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('post-view', kwargs={'pk': self.pk}) views.py: def homeView(request): context = { 'threads': Thread.objects.all().order_by('-created_at'), 'posts': Post.objects.all().order_by('-created_at') } return render(request, 'forum/home.html', context) class ThreadCreateView(CreateView): model = Thread fields = ['title', 'description'] # Right now I also have to add in 'thread' as … -
Reverse for with no arguments not found for URL
I am attempting to create a view that allows users to delete a build log. On the view that shows the delete button with a link to the delete page I am getting the error Reverse for 'build-log-delete' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/build\\-log/(?P<pkz>[0-9]+)/delete$'] If I understand this error correctly its because I am not passing paramaters in the url. <a class="delete-btn" href="{% url 'build-log-delete' %}">Delete</a> However I do not understand why I need to pass parameters in the URL as I am not passing any new values into the URL and if so what parameters I would pass. Do I have to re pass the previous two? urls path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'), path('post/<int:pk>/build-log/<int:pkz>/delete', views.BuildLogDelete, name='build-log-delete') #error views def BuildLogDisplay(request, pk, pkz ): post = BuildLog.objects.filter(post_id=pk) log = BuildLog.objects.get(pk=pkz) context = { 'post':post, 'log':log } return render(request, 'blog/buildlog.html', context) def BuildLogDelete(request): context = { } return render(request, 'blog/BuildLogDelete.html', context) full template <div class="row"> <article class="cars-article"> <div class="flex"> <img class="rounded-circle article-img" src="{{ log.author.profile.image.url }}" /> <div> <a class="article-title">{{ log.title }}</a> </div> </div> <br> <div> {% if log.author == user %} <a class="update-btn" href=""> Update</a> <a class="delete-btn" href="{% url 'build-log-delete' %}">Delete</a> {% endif %} </div> <hr class="solid"> <p class="article-content">{{ log.content … -
Formset is not giving me 3 of the form by default and got KeyError when saving
Hi i have the following error while using formset. Exception Type: KeyError Exception Value: 'module' This error happen when i try to press save on the add page. Currently in my webpage, theres only 1 formset. I read online by default its 3 but even after i add extra=3. Its still 1. Can anyone help me? Here are my codes: views.py def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) ##Part A1 dd_form = DeviceDetailForm(request.POST) #di_form= DeviceInterfaceForm(request.POST) di_formset = modelformset_factory(Device, DeviceInterface, fields=('moduletype', 'firstportid', 'lastportid'), extra = 3) di_form=di_formset(request.POST) if device_frm.is_valid(): # Create and save the device # new_device here is the newly created Device object new_device = device_frm.save() if dd_form.is_valid(): # Create an unsaved instance of device detail deviceD = dd_form.save(commit=False) # Set the device we just created above as this device detail's device deviceD.DD2DKEY = new_device # If you did not render the hostname for the device detail, set it from the value of new device deviceD.hostname = new_device.hostname deviceD.save() if di_form.is_valid(): deviceI=di_form.save(commit=False) deviceI.I2DKEY=new_device deviceI.save() new_device=Device.objects.all() return render(request, 'interface/device_added.html',{'devices':Device.objects.all()}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) else: device_frm = DeviceForm() dd_form = DeviceDetailForm() di_form = DeviceInterfaceForm() return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) … -
bulk_create always causes primary key error (sql server)
Using Django 3.2.6, DB - SQL Server I'm trying to use bulk_create to create a set of rows in my database. In my view, I create a list of Model objects like this and use bulk_create asset_map_list = [] for row in data_list: asset = Asset(asset_type=AssetType.objects.get(name=asset_type_name), asset_name=row['asset_name'], display_name=row['display_name']) asset_list.append(asset) Asset.objects.bulk_create(asset_list) However it keeps throwing a Primary key error django.db.utils.IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Violation of PRIMARY KEY constraint 'PK__mm_asset__xxxxxx' My Asset and Asset Type models look like this: class Asset(models.Model): asset_type = models.ForeignKey(AssetType, on_delete=models.CASCADE) asset_name = models.CharField(max_length=80) display_name = models.CharField(max_length=80) class AssetType(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=80, unique=True) description = models.CharField(max_length=80) I tried setting ignore_conflicts=True but SQL Server doesn't support that. I tried doing df.to_sql() but it gets complicated because of the foreign key (as you can see -- the user inputs asset type NAME but in my asset DB I'm storing asset type ID ) Can someone please help me solve this bulk_create issue or point me to a better alternative? Thanks -
How to deal with empty foreign keys in a for loop within django View
I have a model which acts a as schedule where there are multiple FK relationships to the same user table. All of these fields can be blank/null. The issue is, when i do a for loop, i am trying to match the users based on when they appear on a certain shift, then add a +1 to a counter to get the total shifts for that user. The model looks like this: class WeekdayAssignment(models.Model): """Model definition for WeekdayAssignment.""" start_date = models.DateField(auto_now=False, auto_now_add=False) end_date = models.DateField(auto_now=False, auto_now_add=False) triage_emea_1 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_emea_1", blank=True, null=True) triage_nam_1 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_nam_1", blank=True, null=True) triage_nam_2 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_nam_2", blank=True, null=True) triage_nam_3 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_nam_3", blank=True, null=True) ... As you can see i have 4 triage shifts and the same user can work any of those shifts. I want to do a for loop to count how many times a user is on a shift in any one of those fields. Without getting into all the details of what I am doing, i will keep it simple as the error happens right away. Views.py def someview(request): shift_users = TeamMember.objects.all() weekday_shifts = WeekdayAssignment.objects.all() for t in shift_users: for ws in weekday_shifts: print(ws.triage_nam_3) As long …