Is there an autoincrement-per-user field in Django? - django

I was wondering if there is already a way to create a separate autoincrement-ID-per-user field in Django?
Basically, I'm storing many related models and I need the IDs generated to be autoincrement per user.
I don't want to change how id works, just need a new field that I can add which is unique=True per user.
Any suggestions (other than overriding save and implementing it myself)?

No, there's no such field, but I wonder why you think you need it. The ID is really just for the model's internal use, you shouldn't ever care what it is.
For example, if you want to know how many related items there are for a user then you would just use the count() method on the related queryset. If you want something to be unique per user, you can use the unique_together meta property.
Can you given an example of a use case for a per-user unique id?
Edited in response to comments: to get the object from a URL as you mention, you just need to do:
myuser.myobject_set.all()[7]

Related

Create fields based on another model

I have a User model with some fields. Some of them will require feedback, are they correctly filled (if not, specific message will be displayed on user profile).
The problem is, how to represent 'invalid' fields in database. My idea is to create another model (call it ExtUser) with OneToOneField to User. And ExtUser should have same fields' names as User, but their types will be all boolean, determining whether field is filled in correctly. For example, if User has a field called email:
email = models.CharField(max_length=100)
ExtUser would have following field:
email = models.BooleanField(default=False)
Here's a problem with this approach. How am I supposed to create fields in ExtUser? Of course I can create them manually, but that would be breaking of DRY principle, and I'm not going to do that. The question is, can I add fields to model dynamically, and have them in database (so I assume it would require to be called before migrate)?
I have django 1.8 and I don't want to use any external modules/libraries.
If someone has an another idea of how to represent that data in database, please add comment, not a reply - as this question is about creating fields dynamically.
You will need to do this manually.
Python does not disallow this behavior; you can take a look at this SO response on dynamically created classes, but Django will not be able to interpret the output. In particular, Django relies on the models to create the SQL tables for the application, and there is essentially no way for this to occur if you model is not statically defined.
In this case, I don't think you have to worry much about DRY; if you need a separate model with fields which happen to be related to, but different from, another model, I think it's probably ok.
Finally, I'm unsure what your goal is, but you could probably define some functions which can determine how "correct" the fields of the user are. This is how I would recommend solving this problem (if it applies).

Django accessing fields which are NOT part of a form

I need some clarification as to what the best practice is regarding this. So, say you have a Django form which has many fields that the user can fill out. Say you also have corresponding fields in the models file, but the models file contains some extra fields that the user cannot modify, e.g. unique reference number. Say also, you want to access these hidden fields in the views so that you can present this reference number to the user.
What's the best way of accessing these "hidden" fields that are created when a valid form is submitted? I was thinking of grabbing the latest entry by date, though if there's concurrent requests at the same time, the wrong data may be pulled?
Try using Django's HiddenInput widget. This will allow you to associate data with a form without allowing the user to modify it.

Third-party-app for merging Django user objects?

I need to merge two users in a Django database.
So I wonder if there is any simple way (maybe a dedicated app) to do that?
For example:
We have user_a and user_b and some models that have foreign keys to the User model (Books, Interests, Teams and so on…).
By merging users, I want to delete the object user_b and to set all foreign keys pointing to this object to point to user_a. And – this is my main concern – I want the objects that need to be changed because they reference the to-be-deleted object to be determined automatically without having to specify a list of those Models and foreign key fields in them manually.
Is this already implemented and I'm reinventing the wheel?
Is this possible?
If not, please show me the way to do it: how can I build a list of Django models that have a foreign key to a specific model (User in my case) in runtime?
Thank you for your time.
I found this snippet http://djangosnippets.org/snippets/2283/ . I'm going to have to modify it though, to make it recursive. I will share my code once I'm done.
With Django 1.8 and beyond, you could achieve this robustly using the Model _meta API.
Specifically, you could use Options.get_fields. This will even let you handle generic relations.
You'll need to consider for each related field whether you want to add or replace on merge. This decision depends on your application logic and corresponding schema choices.
u = User.objects.get(pk=123)
related_fields = [
f for f in u._meta.get_fields()
if (f.one_to_many or f.one_to_one)
and not f.concrete
]
for f in related_fields:
# use field's attributes to perform an update

What do I use instead of ForiegnKey relationship for multi-db relation

I need to provide my users a list of choices from a model which is stored in a separate legacy database. Foreign keys aren't supported in django multi-db setups. The ideal choice would be to use a foreign key, but since thats not possible I need to some up with something else.
So instead I created an IntegerField on the other database and tried using choices to get a list of available options.
class OtherDBTable(models.Model):
client = models.IntegerField(max_length=20, choices=Client.objects.values_list('id','name'))
the problem I'm having is that the choices seem to get populated once but never refreshed. How do I ensure that whenever the client list changes that those newest options area available to pick.
What I was really looking for was a way that I could simulate the behavior of a Foreign key field, at least as far as matching up ID's go.
There wasn't a clear way to do this, since it doesn't seem like you can actually specify an additional field when you instantiate a model (you can with forms, easily)
In any case to deal with the problem, since the database is MySQL based, I ended up creating views from the tables I needed in the other database.
To build on #Yuji's answer - if you do self.fields['field'].choices = whatever in the model's __init__, whatever can be any iterable.
This means you can inherit from iterable, and have that object interface to your legacy database, or you can use a generator function (in case you are unfamiliar, look up the yield keyword).
Citing a Django's manual:
Finally, note that choices can be any iterable object -- not necessarily a list or tuple. This lets you construct choices dynamically. But if you find yourself hacking choices to be dynamic, you're probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn't change much, if ever.
Why dont you want just export data from the legacy database and to import it into the new one? This could be done periodically, if the legacy database still in use.

Django inline formset with child of a child

I have three models:
Variable, which has Group as a foreign key
Group, which has Set as a foreign key
Set
I want to create a form that lets user create a new Set based on existing Set. Only things that user is able to modify are the Set name and Variable values.
This has given me an idea of using inlineformset_factory to access models' children. Sadly, all the examples I found go only one layer down.
Is there any way to access the Variables of a Set through inlineformset_factory?
If not - what is a good way to accomplish my goal?
Thank you.
From my experience, it is not worth hacking the existing inlineformset_factory to achieve much beyond what it is meant to do.
You are better off writing a custom view with the qs you want to use and create unique ids for each form element, to identify its parent.